admin管理员组

文章数量:1308173

I want to use URL query to filter my products but when I do this, I only want products that are jeans and are red. For example how can I break the OR relation to an AND relation?

This is my example URL: ?product_tag[0]=jeans&product_tag[1]=red

I'm using Woocomerce.

I want to use URL query to filter my products but when I do this, I only want products that are jeans and are red. For example how can I break the OR relation to an AND relation?

This is my example URL: ?product_tag[0]=jeans&product_tag[1]=red

I'm using Woocomerce.

Share Improve this question edited Jan 6, 2021 at 19:23 fuxia 107k38 gold badges255 silver badges459 bronze badges asked Jan 6, 2021 at 14:54 Wilmar AriasWilmar Arias 1111 bronze badge 1
  • 1 Wilmar, technically WooCommerce questions are off topic, but you can easily edit your question to be just WordPress specific by leaving out the fact that this is for Woo and just changing it so that you're asking about querying tags. :-) To assist, the & in the URL parameters isn't the same as 'AND' in a query, you do not need to change this if that's what you're asking. When you're running a WP_Query you'll set the relation to AND in the actual tax_query. Include your WP_Query code and I'll do what I can to help. – Tony Djukic Commented Jan 6, 2021 at 16:05
Add a comment  | 

1 Answer 1

Reset to default 0
//this is how i added AND filter on product tags 
 
   function product_tag_and_filter( $query ) {
    
        if ( is_admin() || ! $query->is_main_query() ){
            return;
        }
        if(is_product_category()){
    
        $tax_query = array();
    
        // add meta_query elements
        if( !empty( get_query_var( 'product_tag' ) ) ){
            foreach(get_query_var( 'product_tag' ) as $val){
            $tax_query[] = array(  'taxonomy' => 'product_tag', 'field' => 'slug',  'terms' => $val , 'compare' => '=' );
            }
     
        }
    
    
    
        if( count( $tax_query ) > 1 ){
            $tax_query['relation'] = 'AND';
        }
    
        if( count( $tax_query ) > 0 ){
            $query->set( 'tax_query', $tax_query );
        }
    }
    }
    add_action( 'pre_get_posts', 'product_tag_and_filter', 1 );

本文标签: woocommerce offtopicwoocomerce is serving OR Relation instead of AND on taxonomy producttag