Reputation: 53
I just inherited a woocommerce project and I need to change the home page to only show specific brands. They set up a Product-Data => Attribute => pa_brand.
If I print pa_brand array it show me this:
Array
(
[0] => stdClass Object
(
[term_id] => 1134
[name] => Name Brand
[slug] => name-brand
[term_group] => 0
[term_taxonomy_id] => 1134
[taxonomy] => pa_brand
[description] =>
[parent] => 0
[count] => 68
[object_id] => 3385
[filter] => raw
)
)
I'm under the impression I would be able to use the pa_brand to filter the query using one of the key value pairs, preferably the slug, but I'm unsure how to do this. None of the examples I've found has an object, just string results:
$args = array(
'post_type' => array('product', 'product_variation'),
'posts_per_page' => 3,
'orderby' => 'rand',
'meta_query' => array(
array(
'key' => 'pa_brand',
'value' => array('slug' => 'brand-name'),
'compare' => '=',
),
array(
'key' => '_stock_status',
'value' => 'instock',
'compare' => '='
)
)
);
I've tried a lot of variations on this and none of them work. Any suggestions?
Upvotes: 5
Views: 4933
Reputation: 5331
Woocommerce attributes are Taxonomy,
Assuming you'll create a Brand attribute, the url structure is like this,
yoursite.com/wp-admin/edit-tags.php?taxonomy=pa_brand&post_type=product
you see the taxonomy name is pa_brand
now if you create a brand say like Honda under that taxonomy, the url is something like this,
yoursite.com/wp-admin/edit-tags.php?action=edit&taxonomy=pa_brand&tag_ID=6&post_type=product
Where Honda is a tag under the pa_brand
taxonomy with tag id 6
Now to have woocommerce query under specific taxonomy,
We can use WP_query
we can use an argument like this,
$args = array(
'post_type' => 'product',
'taxonomy' => 'pa_brand', // This is the taxonomy slug for brand taxonomy
'term' => 'honda' // This is terms slug of the Honda Brand
);
If you refer on the docs, the argument above is this same as this
$args = array(
'post_type' => 'product',
'tax_query' => array(
array(
'taxonomy' => 'pa_brand',
'field' => 'slug',
'terms' => 'honda',
),
),
);
EDIT: Woocommerce Attributes are taxonomy and not Custom Feilds,
You need to use tax_query
and not meta_query
, taxonomies are saved under wp_term_taxonomy
and wp_terms
database table, While meta_query
is for object query based on Meta field/Custom Field value that are save under wp_postmeta
database table,
https://codex.wordpress.org/Class_Reference/WP_Query
Upvotes: 6