Pull the meta title and description for a post type archive from a page

Control the meta title and description for a post type archive from a Page rather than the Yoast SEO settings


Post type archive pages are automatically generated by WordPress. In some instances, you may want to add content to these pages and therefore create a matching page in the CMS from where you can pull this content and other elements to display it on the archive page.

In the example below, we have a post type archive for Case Studies which is situated at /case-studies/. We also have a page called Case Studies on which we have some additional content including flexible content fields powered by Advanced Custom Fields.

While we can control the SEO meta data from the Yoast SEO plugin under the Content Types tab, it would be easier if we could manage this via the Case Studies page we have in the CMS to keep everything in one place and provide a more consistent content management process.

The code below will pull the meta title from the page with the path case-studies:

/**
 * Use Case Studies SEO title on archive page
 */

function bb_filter_wpseo_title( $title ) { 

    if ( is_post_type_archive('case-studies') ) 
    {

    	$queried_post = get_page_by_path( 'case-studies', OBJECT, 'page' );

    	if ($queried_post)
    	{
    		$queried_post_id = apply_filters( 'wpml_object_id', $queried_post->ID, 'page' );
    		$title = get_post_meta($queried_post_id, '_yoast_wpseo_title' , true);
	    	return $title;
	    }

    } 

    return $title;
}

add_filter( 'wpseo_title', 'bb_filter_wpseo_title', 10, 1 );

The following code will also pull the meta description from the same page:

/**
 * Use Case Studies SEO description on archive page
 */

function b_filter_wpseo_desc( $description ) { 

    if ( is_post_type_archive('case-studies') ) 
    {

    	$queried_post = get_page_by_path( 'case-studies', OBJECT, 'page' );

    	if ($queried_post)
    	{
    		$queried_post_id = apply_filters( 'wpml_object_id', $queried_post->ID, 'page' );
    		$meta_title = get_post_meta($queried_post_id, '_yoast_wpseo_metadesc' , true);
	    	return $description;
	    }

    } 

    return $description;
}

add_filter( 'wpseo_metadesc', 'bb_filter_wpseo_desc', 10, 1 ); 

A lightweight, intuitive WordPress theme to enable flexible developement.

  • Lighting-fast installer
  • Intuitive SASS structure
  • Bloat-free

Build with Barebones