Related Products on product page to show only products from the same sub category

This topic has 4 replies, 2 voices, and was last updated 7 months, 2 weeks ago ago by Rose Tyler

  • Avatar: GNC
    GNC
    Participant
    May 3, 2024 at 10:03

    Hello
    i would like “Related Products” on product page to show only products from the last sub category.

    Please, contact administrator
    for this information.
    3 Answers
    Avatar: Rose Tyler
    Rose Tyler
    Support staff
    May 3, 2024 at 10:13

    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

    Avatar: GNC
    GNC
    Participant
    May 3, 2024 at 10:31

    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 );

    Avatar: Rose Tyler
    Rose Tyler
    Support staff
    May 3, 2024 at 11:03

    Hello,

    We are glad that you sorted it out.

    Best Regards,
    8Theme’s Team

  • Viewing 4 results - 1 through 4 (of 4 total)

You must be logged in to reply to this topic.Log in/Sign up

We're using our own and third-party cookies to improve your experience and our website. Keep on browsing to accept our cookie policy.