WP_Query Woocommerce products that belong in distinct multiple categories only tax_query

后端 未结 4 578
猫巷女王i
猫巷女王i 2021-01-31 21:04

I\'m using WP_Query for Woocommerce products in attempt to query products in a particular category. This is the syntax that worked for me -

$args =         


        
4条回答
  •  梦毁少年i
    2021-01-31 21:13

    Inside a 'tax_query' array's array you can specify an 'operator' to be performed on the query. You can achieve what you want using the 'AND' operator.

    $args = array(
    'posts_per_page' => -1,
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'product_cat',
            'field' => 'slug',
            'terms' => array( 'category-slug1', 'category-slug2' )
            'operator => 'AND',
        ),
    ),
    'post_type' => 'product',
    'orderby' => 'title',
    );
    $the_query = new WP_Query( $args );
    

    All of the products selected by this query will match the provided 'terms'. See this link for more info: https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters

    In case the link ever breaks, here's the relevant info:

    operator (string) - Operator to test. Possible values are 'IN', 'NOT IN', 'AND', 'EXISTS' and 'NOT EXISTS'. Default value is 'IN'.

提交回复
热议问题