How to add Yoast meta description programmatically

posted on by - 3355 views

Yoast SEO is one of the most used, probably the most used, SEO plugins for WordPress. It allows us to easily set some core settings of our websites, with an intuitive interface and useful features that don’t need a specific knowledge of the subject. Anyway I swear I’m not getting any money from them.

One of the most useful features is the possibility to set, for each post and page, a meta title and a meta description, which will be mainly useful for search engines and social networks. If you’re writing a post or a page, you can see this box in the bottom section of the page:

As you can see, Yoast automatically got the title of the post as I’m writing it, but the meta description is still empty here. Clicking on it will give us the ability to edit and save it correctly. But, of course, that’s something we have to do manually.

…and what if we want to do it programmatically, with some PHP code?

How to add the Yoast meta description programmatically

While developing a WordPress theme for a new website I’m working on, I had the following extremely brilliant idea: since I want to save time writing, what if I use the custom meta data stored in my posts to automatically create and save the Yoast meta description?

To do that, we first have to go in our functions.php and create the function that does the job.

function add_yoast_description( $post_id ){
    // Here we can generate the string that will be our Yoast meta description
    // Of course it's your choice how to do that
    $meta_desc = "This is our Yoast meta description. Hurray.";

    $_POST[ "yoast_wpseo_metadesc" ] = $meta_desc;

As you can see, our function accepts an argument, the post ID, that’s sent to it by the hook we’re going to use: save_post.

add_action( 'save_post', 'add_yoast_description' );

Here we go. Now, every time we save a post, the Yoast meta description will be automatically generated and saved.