Skip to content

Snippet: Use Yoast SEO Primary Category for Related WooCommerce Products

The snippet below will alter the default WooCommerce products (this will work with ANY theme) so that they will display related items based on the "Primary Category" as marked by the function in the Yoast SEO Plugin. Important: The related query is "cached" in WordPress via a transient with the name "wc_related_{product_id}" so you either need to delete all the transients on the site to see the instant affect of this snippet or wait for the time to expire.

// Alter related products query to pull items from Yoast Primary Category
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 );
All PHP snippets should be added via child theme's functions.php file or via a plugin. We recommend Code Snippets (100% Free) or WPCode (sponsored)
Back To Top