This topic has 4 replies, 2 voices, and was last updated 5 months, 1 weeks ago ago by Rose Tyler
Hello
i would like “Related Products” on product page to show only products from the last sub category.
Hello,
Thank you for reaching out to us with your request.
Please read this article https://woocommerce.com/document/related-products-up-sells-and-cross-sells/ and contact support of the WooCommerce plugin to get further assistance https://wordpress.org/support/plugin/woocommerce/
Best Regards,
8Theme’s Team
i tried this filter its works:
function wc_related_products_by_last_available_depth_term( $related_posts, $product_id, $args ) {
$product = wc_get_product( $product_id );
$terms = wp_get_post_terms( $product_id, ‘product_cat’ );
$hierarchy = array();
$cat_id = ”;
// find the depth of terms
foreach ( $terms as $key => $term ) {
$ancestors = get_ancestors( $term->term_id, ‘product_cat’ );
if( $ancestors && count( $ancestors ) > 1 ) {
$hierarchy[$term->term_id] = max($ancestors);
}elseif( $ancestors ) {
$hierarchy[$term->term_id] = $ancestors[0];
}
$cat_id = $term->term_id;
}
// if level of depth term available replace $cat_id
if( $hierarchy ){
$cat_id = max( array_keys( $hierarchy ) );
}
$related_posts = get_posts( array(
‘post_type’ => ‘product’,
‘post_status’ => ‘publish’,
‘fields’ => ‘ids’,
‘posts_per_page’ => -1,
‘exclude’ => array( $product_id ),
‘tax_query’ => array(
array(
‘taxonomy’ => ‘product_cat’,
‘field’ => ‘id’,
‘terms’ => array( $cat_id )
)
)
));
return $related_posts;
}
add_filter( ‘woocommerce_related_products’, ‘wc_related_products_by_last_available_depth_term’, 99, 3 );
Hello,
We are glad that you sorted it out.
Best Regards,
8Theme’s Team
You must be logged in to reply to this topic.Log in/Sign up