ProductWoocommerce

Show items in the same Primary category in Related products in Woocommerce

In Woocommerce, we can influence the way that related products are shown in the single product page. When using the Yoast SEO plugin, we have a feature called Primary category. In this case, we can take advantage of the primary category of an item, in order to display related items from the same primary category. We can do that with the snippet bellow, without the need of a plugin.

    
add_filter('woocommerce_related_products', 'custom_related_products_by_primary_category', 10, 3); function custom_related_products_by_primary_category($related_products, $product_id, $args) { // Check if Yoast SEO primary category is set $primary_category_id = get_post_meta($product_id, '_yoast_wpseo_primary_category', true); if ($primary_category_id) { // Get related products by primary category in random order $related_args = array( 'post_type' => 'product', 'posts_per_page' => $args['posts_per_page'], 'post__not_in' => array($product_id), 'fields' => 'ids', 'orderby' => 'rand', 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => $primary_category_id, ), ), ); $related_query = new WP_Query($related_args); $related_products_primary = $related_query->posts; // Fill the remaining related products if needed if (count($related_products_primary) < $args['posts_per_page']) { $args['posts_per_page'] -= count($related_products_primary); $related_products_secondary = get_related_products_by_secondary_categories($product_id, $args); $related_products = array_merge($related_products_primary, $related_products_secondary); } else { $related_products = $related_products_primary; } } else { // Fallback to default related products query if Yoast primary category is not set $related_products = get_related_products_by_secondary_categories($product_id, $args); } return $related_products; } function get_related_products_by_secondary_categories($product_id, $args) { $categories = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'ids')); if ($categories) { $related_args = array( 'post_type' => 'product', 'posts_per_page' => $args['posts_per_page'], 'post__not_in' => array($product_id), 'fields' => 'ids', 'orderby' => 'rand', 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'term_id', 'terms' => $categories, 'operator' => 'IN', ), ), ); $related_query = new WP_Query($related_args); return $related_query->posts; } return array(); }

Leave a Reply