WP_Query Woocommerce products that belong in distinct multiple categories only tax_query

后端 未结 4 613
猫巷女王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条回答
  •  我在风中等你
    2021-01-31 21:29

    To query by category_ID this is what worked for me.

    // First obtain term id:
    //...
    $all_categories = get_categories( $args );
    $cat_ids = array();
    
    foreach ($all_categories as $cat) 
    {
         array_push($cat_ids, $cat->term_id);
    }
    
    //Now use ids from array:
    $args = array(
        'posts_per_page' => -1,
        'post_type' => 'product',
        'tax_query'     => array(
            array(
                'taxonomy'  => 'product_cat',
                'field'     => 'id', 
                'terms'     => $cat_ids
            )
        )
    );
    

提交回复
热议问题