The Yoast SEO plugin for WordPress provides a solid set of hooks that allow you to flexibly manipulate data when building your own meta tags.
In this article, we’ll look at an example where you need to change the site’s title and meta-description for a specific page. The example is simple and is intended to demonstrate how the hooks work. The logic can be customized however you like. For instance, in one of my projects, I had to dynamically generate titles and descriptions depending on the selected region and the services provided. It was a services directory broken down by country, region, city, and category list.
Before you begin, make sure you have the Yoast SEO plugin installed and activated on your site. Otherwise, the rest of the setup won’t make sense.
Now let’s open the functions.php file of your theme and add the following code:
/**
* wpseo_title
*/
add_filter('wpseo_title', function($title){
if(is_single('chto-takoe-lorem-ipsum'))
{
$title = 'New title';
}
return $title;
}, 10, 1);
/**
* wpseo_metadesc
*/
add_filter('wpseo_metadesc', function($metadesc){
if(is_single('chto-takoe-lorem-ipsum'))
{
$metadesc = 'New description';
}
return $metadesc;
}, 10, 1);This code uses two filters:
- wpseo_title — controls the output of the page title
- wpseo_metadesc — controls the output of the page’s meta description
In both filters, we use the WordPress conditional tag is_single to check whether we’re currently viewing the page with the slug chto-takoe-lorem-ipsum. If so, we override the values and return them from the filter.
That’s it 🙂
