Show products with the same attribute as the current product in related products

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

  • Avatar: rasitagac
    rasitagac
    Participant
    November 21, 2023 at 15:51

    I want to show products with the same attribute as the current product in the related products field on the product page. Can you help?

    3 Answers
    Avatar: Rose Tyler
    Rose Tyler
    Support staff
    November 21, 2023 at 17:00

    Hello, Rasitagac,

    Thank you for reaching out to us with your request.

    Please read the next article – https://woocommerce.com/document/related-products-up-sells-and-cross-sells/
    “Related Products is a section on some templates that pulls products from your store that share the same tags or categories as the current product.
    These products cannot be specified in the admin, but can be influenced by grouping similar products in the same category or by using the same tags.”

    Kind Regards,
    8theme team

    Avatar: rasitagac
    rasitagac
    Participant
    November 21, 2023 at 17:13

    The following code works for me

    add_filter( 'woocommerce_related_products', 'related_products_by_attribute', 10, 3 );
    function related_products_by_attribute( $related_posts, $product_id, $args ) {
        $taxonomy   = 'pa_sezon'; // HERE define the targeted product attribute taxonomy
        $term_slugs = wp_get_post_terms( $product_id, $taxonomy, ['fields' => 'slugs'] ); // Get terms for the product
        if ( empty($term_slugs) )
            return $related_posts;
        $posts_ids = get_posts( array(
            'post_type'            => 'product',
            'ignore_sticky_posts'  => 1,
            'posts_per_page'       => 4,
            'post__not_in'         => array( $product_id ),
            'tax_query'            => array( array(
                'taxonomy' => $taxonomy,
                'field'    => 'slug',
                'terms'    => $term_slugs,
            ) ),
    		'meta_query'           => array( array(
                'key'     => '_stock_status',
                'value'   => 'instock',
                'compare' => '=',
            ) ),
            'fields'  => 'ids',
            'orderby' => 'date',
        ) );
        return count($posts_ids) > 0 ? $posts_ids : $related_posts;
    }
    Avatar: Rose Tyler
    Rose Tyler
    Support staff
    November 21, 2023 at 17:19

    Hello, Rasitagac,

    Thank you for letting us know.

    Kind Regards,
    8theme team

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

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

Helpful Topics

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