简体   繁体   中英

WooCommerce related products filtered by attribute

I've looked at this question and this one but I'm still stuck.

I have an attribute of "status" and I only want classes (products) with the value of "OPEN" to appear. I'm editing the related.php WooCommerce template file.

Here are two versions of code I've tried.

Version 1:

 $args = apply_filters( 'woocommerce_related_products_args', array(
'post_type'            => 'product',
'ignore_sticky_posts'  => 1,
'no_found_rows'        => 1,
'posts_per_page'       => $posts_per_page,
'orderby'              => $orderby,
'post__in'             => $related,
'post__not_in'         => array( $product->id ),
'meta_query' => array(
   array(
    'key' => 'status',
    'value' => 'OPEN',
   ),
 ),
 ) );

Version 2:

    $key="status";
    $value="OPEN";
    $query_status = array('meta_key' => $key, 'meta_value' => $value);
    $meta_query[] = $query_status;

    $args = apply_filters( 'woocommerce_related_products_args', array(
    'post_type'            => 'product',
    'ignore_sticky_posts'  => 1,
    'no_found_rows'        => 1,
    'posts_per_page'       => $posts_per_page,
    'orderby'              => $orderby,
    'post__in'             => $related,
    'post__not_in'         => array( $product->id ),
    'meta_query'           => $meta_query,
     ) );

    $products                    = new WP_Query( $args );

The first version causes no related products to show up, so it breaks the code. the second has no effect.

How can I solve this issue?

Thanks

Okay, I have the answer! WooCommerce stores custom attributes a couple of ways, but in this case I needed to use the term query instead of the meta query. Here's the final query, works like a charm:

$args = apply_filters( 'woocommerce_related_products_args', array(
       'post_type'            => 'product',
       'ignore_sticky_posts'  => 1,
       'no_found_rows'        => 1,
       'posts_per_page'       => 4,
       'orderby'              => $orderby,
       'post__not_in'         => array( $product->id ),
       'tax_query'      =>     array(
              array(
                      'taxonomy' => 'pa_status',
                      'field' =>      'slug',
                      'terms' => 'open'
              )
        )
) );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM