How To Update Yoast SEO Fields Programmatically

masterjosh
by
masterjosh
Apr 03, 2019
How To Update Yoast SEO Fields Programmatically

The regular WordPress user generally publishes their new articles by pressing the “Publish” button on the WordPress dashboard. Or maybe by scheduling the post for automatic publishing sometime in the future.

This code sample is for developers who use Yoast SEO plugin on their blog and want to publish a post using PHP code. It’s a quick copy and paste method to update Yoast SEO fields.

Create this PHP function:


function add_to_yoast_seo($post_id, $metatitle, $metadesc, $metakeywords){
    $ret = false;
    // Include plugin library to check if Yoast Seo is presently active
    include_once( ABSPATH.'panel/includes/plugin.php' );
    if(is_plugin_active(ABSPATH.'wp-content/plugins/wordpress-seo/wp-seo.php')) {
        //plugin is activated
        $updated_title = update_post_meta($post_id, '_yoast_wpseo_title', $metatitle);
        $updated_desc = update_post_meta($post_id, '_yoast_wpseo_metadesc', $metadesc);
        $updated_kw = update_post_meta($post_id, '_yoast_wpseo_metakeywords', $metakeywords);
        if($updated_title && $updated_desc && $updated_kw){
            $ret = true;
        }
    }
    return $ret;
}

And call it like this:


$seo_updated = add_to_yoast_seo(
    $post->ID,
    'My Seo Title',
    'My Seo Description',
    'my, seo, kewywords'
);

If you just want to retrieve the yoast title or meta description fields for an already published post, just grab them like this:


$MyPostMeta = get_post_meta($post->ID, '_yoast_wpseo_metadesc', true);
$MyPostTitle = get_post_meta($post->ID, '_yoast_wpseo_title', true);




Add Comment