0

I want to display products that are related either by category or attributes (not tags)

I've modified the solution posted here here to my needs:

function custom_related_product_args ( $args ){
    global $product;

    $cats          = wc_get_product_terms( $product->id, 'product_cat', array( 'fields' => 'slugs' ) );
    $brands        = wc_get_product_terms( $product->id, 'pa_brand', array( 'fields' => 'slugs' ) );
    $collections   = wc_get_product_terms( $product->id, 'pa_collection', array( 'fields' => 'slugs' ) );    

    unset( $args['post__in'] );
    $args['tax_query'] = array( 
        'relation' => 'OR',
        array(
            'taxonomy' => 'product_cat',
            'field'    => 'slug',
            'terms'    => $cats,
        ),
        array(
            'relation' => 'OR',
            array(
                'taxonomy' => 'pa_brand',
                'field'    => 'slug',
                'terms'    => $brands,
            ),
            array(
                'taxonomy' => 'pa_collection',
                'field'    => 'slug',
                'terms'    => $collections,
            )
        )
    );

    return $args;
}
add_filter('woocommerce_related_products_args', 'custom_related_product_args');

However it doesn't seem to work for me and I can't figure out what I'm doing wrong?

0
global $product;

$cats          = wc_get_product_terms( $product->id, 'product_cat', array( 'fields' => 'slugs' ) );
$brands        = wc_get_product_terms( $product->id, 'pa_brand', array( 'fields' => 'slugs' ) );
$artists       = wc_get_product_terms( $product->id, 'pa_artist', array( 'fields' => 'slugs' ) );    
$manufacturers = wc_get_product_terms( $product->id, 'pa_manufacturer', array( 'fields' => 'slugs' ) );

unset( $args['post__in'] );
$args['tax_query'] = array( 
    'relation' => 'AND',
    array(
        'taxonomy' => 'product_cat',
        'field'    => 'slug',
        'terms'    => $cats,
    ),
    array(
        'relation' => 'OR',
        array(
            'taxonomy' => 'pa_brand',
            'field'    => 'slug',
            'terms'    => $brands,
        ),
        array(
            'taxonomy' => 'pa_artist',
            'field'    => 'slug',
            'terms'    => $artists,
        ),
        array(
            'taxonomy' => 'pa_manufacturer',
            'field'    => 'slug',
            'terms'    => $manufacturers,
        )
    )
);

return $args;
  • Where do I place the code? I tried it in functions.php but doesn't seem to make a change in the output – Dan Feb 18 '18 at 16:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.