Home / Blog / E-commerce
,

Best method to show Related Products using Yoast Primary Category

First published 25 Jul 2020. Tested again in November 2026 on WordPress 7.1.4, WooCommerce 11.2.2, Yoast SEO and PHP 8.4.

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.

Dhiren Patel

Principal Full-Stack Engineer · Founder, Exivon Tech

I’ve built and run enterprise web platforms and e-commerce for 13 years, and I built ShieldScope, a free WordPress security scanner, and Lede, a free block theme.

2 responses to “Best method to show Related Products using Yoast Primary Category”

  1. Saket

    Hi
    I use rankmath pro. Can you please tell me the code for rankmath? I selected a primary category using rankmath.

    Thanks

    1. Dhiren Patel

      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.

      $terms = wc_get_product_category_list( $arguments );
      $terms[0]; // This will be the Pirmary term.
      

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.