Use Yoast SEO meta title in site search

Yoast SEO lets you customize the meta title for your content, which is used in Google search results and browser tabs.

Since these are often more descriptive than the actual page title, I recommend using them in your on-site search results as well. (I also recommend using SearchWP for improved site search).

Yoast SEO stores the meta title as post metadata, using the key _yoast_wpseo_title. But don’t output this directly – the titles often include dynamic variables like %%title%% for the post title.

You can use wpseo_replace_vars( $string, $post ) to replace the variables with actual text. You should also provide fallbacks for if (a) Yoast SEO is no longer active, and (b) no custom title was provided.

$title = '';
if( is_search() && function_exists( 'wpseo_replace_vars' ) ) {
	global $post;
	$title = get_post_meta( get_the_ID(), '_yoast_wpseo_title', true );
	$title = wpseo_replace_vars( $title, $post );
}
if( empty( $title ) ) {
	$title = get_the_title();
}

Bill Erickson

Bill Erickson is a freelance WordPress developer and a contributing developer to the Genesis framework. For the past 14 years he has worked with attorneys, publishers, corporations, and non-profits, building custom websites tailored to their needs and goals.

Ready to upgrade your website?

I build custom WordPress websites that look great and are easy to manage.

Let's Talk