Snippets: Use Yoast SEO Primary Category For Related Blog Posts

This code will alter the way the related blog posts work so if you have a primary category defined for the current post then the related items will be based on this category. Otherwise it will pull items from other categories defined by the post.

// Use Yoast SEO Primary Category For Related Blog Posts
add_filter( 'wpex_blog_post_related_query_args', function ( $args ) {
	
	// Check for primary category and if it exists change the
	// query args to pull other posts from this primary category only
	if ( class_exists( 'WPSEO_Primary_Term' ) ) {
		$primary_term = new WPSEO_Primary_Term( $taxonomy, $post_id );
		$primary_term = $primary_term->get_primary_term();
		if ( $primary_term ) {
			$get_primary_term = get_term( $primary_term, $taxonomy );
			$terms = array( $get_primary_term );
			$cats['category__in'] = array( $terms );
		}
	}

	// Return args
	return $args; 

} );

Snippet Type: PHP

Posted Under: Blog

All PHP snippets should be added via a child theme's functions.php file.