WordPress automatic meta description generation

Sometimes you’re just too lazy to create proper meta descriptions for a post or page and having a good(ish) meta description to display in your SERP is rather important for SEO.

I recently had to write a plugin to generate meta descriptions for all post types. The theory is, when you request the page, I have an action that runs on the

add_action('wp_head', 'xxx');

action. It then checks if you have a meta description for that page (assuming you have Yoast SEO installed), and if not, generates one based on a few parameters and appends it to your

<head></head>

section in your markup.

I’ll give you a base to start off with, this is by no means a complete and final version that you should use on your site. There is a lot more validation that needs to be done, but it’s a start. For now, you can put this in your functions.php file.

The bit of code below will check if you have a Yoast SEO meta description, if not, it will take the first sentence it finds in your content and use that as a meta description. Meta descriptions are 160 characters in length, anything over that will be truncated by Google.

add_action('wp_head', 'my_generate_custom_meta');

function my_generate_custom_meta() {
	global $wp_query;
	$yoast_meta_key = '_yoast_wpseo_metadesc';
	$post_id = get_the_ID();
	$yoast_meta_desc = get_post_meta($post_id, $yoast_meta_key, true);

	if (empty($yoast_meta_desc)) {
		$meta_desc = '';
		$title = strip_tags($wp_query->queried_object->post_title);
		$content = strip_tags($wp_query->queried_object->post_content);

		if (!empty($title) && !empty($content)) {
			$first_sentence = substr($content, 0, strpos($content, '.'));
			$meta_desc = $title . '. ' . $first_sentence;
			update_post_meta($post_id, $yoast_meta_key, $meta_desc);
			echo sprintf('', $meta_desc);
		}
		
	}
}