Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WooCommerce get products by attribute query

I have a product with attribute colors. Attribute values are red, blue and green. I am trying to create a custom search but I can't get the query to pull any product.

$args =  array(
    'post_type'      => array('product'),
    'post_status'    => 'publish',
    'posts_per_page' => -1,
    'meta_query'     => array( 
        array(
            'key' => '_visibility',
            'value' => array('catalog', 'visible'),
            'compare' => 'IN',  
        ) 
    ),
    'tax_query'      => array( 
        array(
            'taxonomy'        => 'product',
            'field'           => 'slug',
            'terms'           =>  array('blue', 'red', 'green'),
            'operator'        => 'IN',
        ),
    )
);

$products = new WP_Query( $args );

Where did I go wrong?

like image 829
user3098629 Avatar asked Aug 23 '17 00:08

user3098629


People also ask

How do I get a list of products in WooCommerce?

In the WordPress admin, go to WooCommerce > Settings > Products > Product tables. Add your license key and read through all the settings, choosing the ones that you want for your WooCommerce all products list.

What is product attribute WooCommerce?

First is via WooCommerce widgets. “Filter Products by Attribute” allows you to select a specific attribute. If you add this widget to your sidebar, customers can filter products in your store based on the attribute. Second is via variable products.


1 Answers

The correct taxonomy for the product attribute color is 'pa_color', so the correct working query is:

// The query
$products = new WP_Query( array(
   'post_type'      => array('product'),
   'post_status'    => 'publish',
   'posts_per_page' => -1,
   'meta_query'     => array( array(
        'key' => '_visibility',
        'value' => array('catalog', 'visible'),
        'compare' => 'IN',
    ) ),
   'tax_query'      => array( array(
        'taxonomy'        => 'pa_color',
        'field'           => 'slug',
        'terms'           =>  array('blue', 'red', 'green'),
        'operator'        => 'IN',
    ) )
) );

// The Loop
if ( $products->have_posts() ): while ( $products->have_posts() ):
    $products->the_post();
    $product_ids[] = $products->post->ID;
endwhile;
    wp_reset_postdata();
endif;

// TEST: Output the Products IDs
print_r($product_ids);

This code is tested and works. You will get all products that have Color attribute with the values (terms) 'blue', 'red' and 'green'…

Since WooCommerce 3, product visibility is handled by custom taxonomy product_visibility. You can see the following related threads:

  • Database changes for products in woocommerce 3
  • Get products which are visible in catalog in a WP_query on Woocommerce
like image 195
LoicTheAztec Avatar answered Sep 22 '22 18:09

LoicTheAztec