简体   繁体   中英

List all product categories with simple products

I want to get all the product categories and simple product count from woocommerce with product type simple. If i pass the below code snippet to get_categories($args); I get all the product categories How can i restrict to get only the categories with simple products?

$cat_args = array(
    'hide_empty' => 0,
    'taxonomy' => 'product_cat',
    'hierarchical' => 1,
    'orderby' => 'name',
    'order' => 'ASC',
    'child_of' => 0,
    'pad_counts' => true,
    

);

i tried as below but it does not work.

$cat_args = array(

    'tax_query'      => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'product_cat',
            'hide_empty' => 0,
            'hierarchical' => 1,
            'orderby' => 'name',
            'order' => 'ASC',
            'child_of' => 0,
            'pad_counts' => true
        ),
        array(
            'taxonomy' => 'product_type',
            'field'    => 'slug',
            'terms'    => array('simple')
        ),

    ),

);

The below code is fine, you just have to include the meta query to the end, so you can get the categories that have one or more simple product.

$cat_args = array(
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'product_cat',
            'hide_empty' => 0,
            'hierarchical' => 1,
            'orderby' => 'name',
            'order' => 'ASC',
            'child_of' => 0,
            'pad_counts' => true
        ),
        array(
            'taxonomy' => 'product_type',
            'field'    => 'slug',
            'terms'    => array('simple')
        ),
    ),
    'meta_query' => array(
        'relation' => 'AND',
        array(
            'key' => '_product_type',
            'value' => 'simple',
            'compare' => '='
        )
    ),
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM