Restrict related products to same category only
-
Prior to WC 3.5 my client’s site had a piece of code (inside related.php template v1.6.4) that created a modified WC loop for related products only showing the ones in the current product’s category.
if ( ! defined( 'ABSPATH' ) ) { exit; } global $product, $woocommerce_loop; if ( empty( $product ) || ! $product->exists() ) { return; } $cats_array = array(0); $terms = wp_get_post_terms( $product->id, 'product_cat' ); if( sizeof( $terms ) ){ foreach ( $terms as $term ) { $children = get_term_children( $term->term_id, 'product_cat' ); if ( !sizeof( $children ) ) $cats_array[] = $term->term_id; } } $args = apply_filters( 'woocommerce_related_products_args', array( 'post_type' => 'product', 'ignore_sticky_posts' => 1, 'no_found_rows' => 1, 'posts_per_page' => $posts_per_page, 'orderby' => $orderby, 'post__in' => $related, 'post__not_in' => array( $product->id ), 'tax_query' => array( array( 'taxonomy' => 'product_cat', 'field' => 'id', 'terms' => $cats_array ), ) ) ); $products = new WP_Query( $args ); $woocommerce_loop['name'] = 'related'; $woocommerce_loop['columns'] = apply_filters( 'woocommerce_related_products_columns', $columns ); if ( $products->have_posts() ) : ?> <div class="related products"> <h2><?php _e( 'Related Products', 'woocommerce' ); ?></h2> <?php woocommerce_product_loop_start(); ?> <?php while ( $products->have_posts() ) : $products->the_post(); ?> <?php wc_get_template_part( 'content', 'product' ); ?> <?php endwhile; // end of the loop. ?> <?php woocommerce_product_loop_end(); ?> </div> <?php endif; wp_reset_postdata();
With 3.5 it stopped working. The template code changed significantly, in v3.0.0.
$related_products
is used instead of$products
so everything else does not apply. Even sticking with the old template doesn’t work.This is essential for this site since it’s an art gallery where categories are artists and products are artworks. So they need to display other works by the same artist on each individual artwork page.
Please help!
The page I need help with: [log in to see the link]
- The topic ‘Restrict related products to same category only’ is closed to new replies.