2

As many other users, i'm using also related products for my shop. I tried to modify it so that it's replacing the last word with the active category name. So when the product is in the category Bed, the related product text is These are our favourite Beds. Is the category pillow it's These are our favorites pillows and so on. The clue is that it's allways using the active category.

Example: Sleep (Parent Category) > Pillow (subcategory) >Product name. In this case it will display pillow.

Example: Sleep > Product name .In this case it's using the word sleep.

The problem that i have now is that it should only use the products from the same category. So when it's pillow it should display only pillows, but in my case it's also shows products from the parent category. How can i fix that, so that it's only displaying products from the active category?

// Rename Related Products
function get_favorite_category_title_for( $product_id ) {
    $title = __('This could be interesting', 'woocommerce');

    $cats = $cats = wp_get_post_terms( $product_id, 'product_cat', array('orderby'=> 'id', 'order'=>'DESC') );
    if( count($cats) > 0 ) {
        $title = __( 'Unsere beliebtesten ', 'woocommerce' ) . $cats[0]->name;
    }
    return $title;
}
LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399
p_e_88
  • 1,029
  • 11
  • 24

1 Answers1

1

Try the following untested code without any guaranty (based on some other related answers):

add_filter( 'woocommerce_related_products', 'filter_woocommerce_related_products', 10, 3 );
function filter_woocommerce_related_products( $related_posts, $product_id, $args  ){
    // Get the product categories
    $terms = wp_get_post_terms( $product_id, 'product_cat' );

    $related_posts = wc_get_products( array(
        'status'    => 'publish',
        'limit'     => -1,
        'category'  => array(reset($terms)->slug),
        'orderby'   => 'ID',
        'order'     => 'DESC',
        'return'    => 'ids',
    ) );

    return $related_posts;
}

Code goes on function.php file of your active child theme (or active theme). It could works.

LoicTheAztec
  • 229,944
  • 23
  • 356
  • 399