I want to display product sliders with “related products” only those in its same primary category (I set using Yoast SEO), however using this snippet it doesn’t work, can you help to check what is wrong, thanks!
add_filter( ‘woocommerce_product_related_posts_query’, ‘ml_related_products_primary_or_default’, 10, 2 );
function ml_related_products_primary_or_default( $query, $product_id ) {
// Make sure Yoast SEO Exist
if ( ! class_exists( ‘WPSEO_Primary_Term’ ) ) {
return $query;
}
// Get Primary Category
$primary_term = new WPSEO_Primary_Term( ‘product_cat’, $product_id );
$primary_cat_id = $primary_term->get_primary_term();
// fallback
if ( ! $primary_cat_id || $primary_cat_id <= 0 ) {
return $query;
}
// Use Primary Category
$primary_args = $query;
$primary_args['tax_query'] = array(
array(
'taxonomy' => ‘product_cat’,
‘field’ => ‘term_id’,
‘terms’ => array( $primary_cat_id ),
),
);
$related_products = get_posts( $primary_args );
// At least 6 paroducts to use Yoast Primary Category
if ( count( $related_products ) < 6 ) {
return $query; // Back to WooCommerce default
}
return $primary_args; //
}