How to Show Related Products by Attribute – WooCommerce

WooCommerce provides documentation on how to change the number of related products shown on a product page. Is there a way to change how they are related? It seems they are currently being related by category. Is there a way to show related products based on a single attribute?

Filter Below:

<?php
/**
 * WooCommerce Extra Feature
 * --------------------------
 *
 * Change number of related products on product page
 * Set your own value for 'posts_per_page'
 *
 */ 
function woo_related_products_limit() {
  global $product;

    $args = array(
        'post_type'             => 'product',
        'no_found_rows'         => 1,
        'posts_per_page'        => 6,
        'ignore_sticky_posts'   => 1,
        'orderby'               => $orderby,
        'post__in'              => $related,
        'post__not_in'          => array($product->id)
    );
    return $args;
}
add_filter( 'woocommerce_related_products_args', 'woo_related_products_limit' );

Related posts

Leave a Reply

2 comments

  1. The filter woocommerce_related_products_args does not exist anymore. You can look into the function wc_get_related_products() to find which filters are currently available.

    To replace categories by a single product attribute, I used the following code in my functions.php:

    add_filter( 'woocommerce_get_related_product_cat_terms', 'my_attribute_relation', 10, 2);
    /** Find related products using the attribute `pa_myAttrib`, throw away product categories. */
    function my_attribute_relation( $original_term_ids, $product_id ) {
      return wc_get_product_term_ids( $product_id, 'pa_myAttrib' );
    }
    

    In this case, product related by tags are kept. If you want to alter those, add a filter for woocommerce_get_related_product_tag_terms, too.

  2. You should be able to do it by the taxonomy feature in wp_query… link

    The attribute you want to target is ‘woocommerce_attributes’, not tested but this should work:

    $args = array(
        'post_type'             => 'product',
        'no_found_rows'         => 1,
        'posts_per_page'        => 6,
        'ignore_sticky_posts'   => 1,
        'orderby'               => $orderby,
        'post__in'              => $related,
        'post__not_in'          => array($product->id),
        'woocommerce_attributes' => 'attribute_slug',
    );
    return $args;