Wordpress: WP_Query posts according to their primary category / taxonomy

Views: 202·Likes:

Yoast SEO is a great plugin that among other features it enables you to choose a primary category (or taxonomy) for your post or custom post type.

Recently i made a project where i had to use WP_Query to fetch posts according to their primary category.

Specifically, i had a custom post type called ‘recipe’ and a custom taxonomy for it, called ‘recipe_characteristic’. When a user would read the recipe on the site, at the bottom of the page i needed to show a list of related recipes that would have the same primary taxonomy and not just to belong under the same taxonomy, as a recipe could belong under multiple taxonomies.

Using Yoast primary taxonomy feature

HOW TO USE WP_QUERY TO GET POSTS ACCORDING TO THEIR PRIMARY TAXONOMY OR PRIMARY CATEGORY

First, you need to find the primary taxonomy for your current post.

In this case, according to the linked post above, to get the primary taxonomy it would be:

$recipe_characteristics = get_post_primary_category($post->ID, 'recipe_characteristic');
$primary_characteristic = $recipe_characteristics['primary_category'];

After getting the primary taxonomy, it is time for the actual WP_Query:

$related_recipes = new WP_Query(array(
	'post_type' => 'recipe',
	'post_status' => 'publish',
	'posts_per_page' => 4,
	'post__not_in' => array($this_post->ID),
	'update_post_meta_cache' => false,
	'update_post_term_cache' => false,
	'ignore_sticky_posts' => true,
	'orderby' => 'rand',
	'tax_query' => array(
		array(
			'taxonomy'  => 'recipe_characteristic',
			'field'     => 'term_id',
			'terms'     => $primary_characteristic->term_id
		)
	),
	'meta_query' => array(
		array(
			'key' => '_yoast_wpseo_primary_recipe_characteristic',
			'value' => $primary_characteristic->term_id,
		)
	),
));

So you make a simple WP_Query, stating the tax_query as you would normally do and also add an extra meta_query.

The key is to use the _yoast_wpseo_primary_xxxkey in the meta_query which you can alter according to your taxonomy name eg

_yoast_wpseo_primary_category or _yoast_wpseo_primary_project_category etc.

Notes:

I chose to remove the current recipe from the results by stating:

'post__not_in' => array($this_post->ID),

And i also added a random order for the results:

'orderby' => 'rand',