Forum Replies Created

Viewing 1 post (of 1 total)
  • Avatar: rasitagac
    rasidagac
    Participant

    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;
    }
Viewing 1 post (of 1 total)