skip to Main Content

So, I know you can put:

function page_title_sc( ){
   return get_the_title();
}
add_shortcode( 'page_title', 'page_title_sc' );

Into function.php to fetch the page title and get a [page_title] shortcode within WordPress, but is it possible to do exactly that for keywords?

I put a focus keyword down in Yoast SEO and I would like to have a shortcode for that.

Or another idea: is there a way to have a custom shortcode field in every page? So that I only have to put something into that once and can use it as a shortcode within the whole page?

3

Answers


  1. Use get_post_meta and grab _yoast_wpseo_focuskw:

    function page_focus_keyword( ){
       return get_post_meta(get_the_ID(), '_yoast_wpseo_focuskw');
    }
    add_shortcode( 'focus_keyword', 'page_focus_keyword' );
    
    Login or Signup to reply.
  2. If you want a shortcode for Yoast to output the keyphrase automatically:

    function wpso_61018203_output_yoast_keyphrase() {
        // Make sure Yoast is installed/active.
        if ( class_exists( 'WPSEO_Meta' ) ) :
            // Hold the global post object.    
            global $post;
    
            return WPSEO_Meta::get_value( 'focuskw', $post->ID );
        endif;
    }
    
    add_shortcode('yoast_kw', 'wpso_61018203_output_yoast_keyphrase' );
    

    You can then do this ['yoast_kw'] in your content, or use echo do_shortcode('[yoast_kw]'); in your template.

    Login or Signup to reply.
  3. WordPress filters all content to make sure that no one uses posts and page content to insert malicious code in the database. This means that you can write basic HTML in your posts, but you cannot write PHP code.

    And you want to use WordPress shortcode for focus keyword.

    Possible solution given on WordPress.org Yoast SEO plugin support query on similar query, and checkout the linked solution

    insert the below php snippet in functions.php

    if(!function_exists('wpseoFocusKW'))
    {
            function wpseoFocusKW()
            {
                $focuskw = wpseo_get_value('focuskw', $post->ID);
                echo $focuskw;
            }
    }
    

    And to use the shortcode in another page for focused keyword, insert the below shortcode in any pages with yoast-seo plugin :

    Shortcode for focus keyword

     [<?php wpseoFocusKW();?>]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search