1
votes

I've been searching for many blogs and forum but this seems not yet answered yet. So i am trying to find a way how to filter product by attribute. I am using ajax to pull data and append it.The question is what will be the query to make a loop depend on what attribute.

Example.
Product A has Color:Blue,Red,Green and has a brand : BrandA , BrandB
Product B has Color:Pink,Red,black.

All i want is to get all product with an attribute of Color [red and green] and Brand [BrandA] in a single query without using any plugin. Here my code in my functions.php

function advanced_search(){

     $html = "";
     $args = array( 'post_type' => 'product','product_cat' => 'yarn');
     $loop = new WP_Query( $args );
     while ( $loop->have_posts() ){
         $loop->the_post();
         ob_start();
         get_template_part( 'templates/part', 'search-result' ); 
         $html = ob_get_contents();
         ob_end_clean();
     }  
     wp_send_json(array(  "product_id" => $product_id , "html"  => $html ));
}
add_action('wp_ajax_get_advanced_search', 'advanced_search');
add_action('wp_ajax_nopriv_get_advanced_search', 'advanced_search'); 

I dont know where should i put the product attributes in my query. I hope anyone found an answer for this.Thank you very much.

1

1 Answers

6
votes

You should be able to achieve what you're looking to do by using a tax_query combined with your WP_Query. Attached is a small example using a 'Brand' attribute and the 'EVGA' term inside it (which WooCommerce will turn into 'pa_brand' - product attribute brand).

$query = new WP_Query( array(
    'tax_query' => array(
        'relation'=>'AND',
        array(
            'taxonomy' => 'pa_brand',
            'field' => 'slug',
            'terms' => 'evga'
        )
    )
) );

You can find some more documentation on the above links to string a few tax queries together for additional filtering and functionality.