Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query WooCommerce Products based on Attribute

This one's driving me nuts.. I'm trying to query and output WooCommerce products based on a specific attribute. For example, I set up an Attribute called on, with possible values of yes or no.

I query using the following:

$args = array(  
   'post_type' => 'product',  
   'meta_key' => 'pa_on',  
   'meta_value' => 'yes',  
   'posts_per_page' => -1  
);  

query_posts($args);

The meta_key is crucial perhaps; if I call it on I get nothing. If I call it pa_on (because that's how I understand WooCommerce custom attributes to be constructed) I get nothing.

However, if I try a different query and use _featured, which is a standard WooCommerce custom meta thingy, it returns the relevant featured posts. Help, anyone?

like image 553
Ian Yates Avatar asked Jan 14 '14 18:01

Ian Yates


People also ask

How do I get the attribute of a product in WooCommerce?

Add global attributes to product Add the created attributes to your products. Go to: Products > Add Product (or edit an existing one). Select the Attributes tab in the Product Data. There you can choose any of the attributes that you've created in the dropdown menu.

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. Now create a page where you want to list all products in a table (Pages > Add New.


1 Answers

I know this is an old one, but just in case someone stumbles upon it like I did today -- Woocommerce (I'm using v2.6.2) appears to store these custom attributes as taxonomies.

I suspect the correct args for the original question would look like this:

  $args = array(
    'post_type' => 'product',
    'tax_query' => array(
      array(
        'taxonomy' => 'pa_on',
        'field'    => 'name',
        'terms'    => 'yes'
      )
    )
  );

Using the appropriate values for my installation, it solved my problem.

like image 122
hcd00045 Avatar answered Oct 10 '22 18:10

hcd00045