Wordpress Shortcode for keywords?

Viewed 402

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

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.

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' );

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();?>]
Related