WooCommerce with Yoast SEO plugin is the best combination for your online store to have a good SEO score. Yoast SEO provides a primary category feature that helps you point out which product category is more important for a particular post if you select multiple product categories for the product.
As we have the primary product category for the product selected, it’s better to show products of the same primary product category as related products on the product detail page. Add below code in functions.php file of your active theme to show products from the same Yoast primary category as related products in WooCommerce.
/**
* Show related products from Yoast Primary Category in WooCommerce
*/
add_filter( 'woocommerce_get_related_product_cat_terms', function( $terms, $product_id ) {
if ( function_exists( 'yoast_get_primary_term_id' ) ) {
$primary_term_product_id = yoast_get_primary_term_id( 'product_cat', $product_id );
if ( $primary_term_product_id ) {
return array( $primary_term_product_id );
}
}
return $terms;
}, 10, 2 );View or fork this snippet on GitHub Gist.
Want this checked on your own site? See Exivon Tech’s Website & E-commerce Audit.




2 responses to “Best method to show Related Products using Yoast Primary Category”
Hi
I use rankmath pro. Can you please tell me the code for rankmath? I selected a primary category using rankmath.
Thanks
Hi Saket,
If you are using Rank Math SEO plugin, please use the wc_get_product_category_list function to get all the terms that are assigned to a product. The first term which the function returns will be the primary term.