0

I need to get all product in a category that match an attribute.

Here my code:

$title     = isset($instance['title']) ? $instance['title'] : '';
$car_type  = isset($instance['cartype']) ? $instance['cartype'] : 'usato';
$car_brand = isset($instance['carbrand']) ? $instance['carbrand'] : '';
$limit     = isset($instance['limit']) ? $instance['limit'] : null;
$order     = $instance['order'];
$carousel  = $instance['carousel'];


$query_args = [
    'post_type'   => 'product',
    'post_status' => 'publish',
    'product_cat' => $car_type                
 ];

 // Ordino i risultati
 if ($order == 'random') {
     $query_args['orderby'] = 'random';
 } else {
     $query_args['orderby'] = 'name';
     $query_args['order']   = $order;
 }

 // Devo limitare il numero di risultati?
 if ($limit) {
     $query_args['posts_per_page'] = $limit;
 }

 if ($car_brand != '') {
     $query_args['tax_query'] = array(
         array(
             'key'     => 'pa_marca',
             'value'   => 'nike',
             'field'   => 'slug',
             'compare' => '='
         )
     );
 }

The problem is that I always get 0 result even if there is a product with that category and that attribute.
How should I modify the query?

0

Finally I get the solution, this is how you need to query on an attribute:

$query_args['tax_query'] = array(
    array(
        'key'     => 'pa_brand',
        'field'   => 'slug',
        'terms'   => 'nike'
    )
);

Note that in the key you need to add pa_ to your attribute name and you need to use terms to specify the value of your attribute.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.