WooCommerce: function that returns all product ID&

2020-07-30 03:12发布

I think the title of the question is fairly self-explanatory, but to detail it...

I'm trying to make a custom category page in Woocommerce.

What I need is to return all the product ID's in a particular category.

I've seen this post, but it uses the WP_Query way of doing things, which is pretty ugly.

I'd prefer to use something in the WooCommerce classes to accomplish this.

Ideally, there should some sort of function/method like the following (but I can't find it):

get_products_in_category( $category_ID );
// Returns array of product ID's

Any help would be amazing.

1条回答
一纸荒年 Trace。
2楼-- · 2020-07-30 03:53

Here you are:

function get_products_from_category_by_ID( $category_id ) {

    $products_IDs = new WP_Query( array(
        'post_type' => 'product',
        'post_status' => 'publish',
        'fields' => 'ids', 
        'tax_query' => array(
            array(
                'taxonomy' => 'product_cat',
                'field' => 'term_id',
                'terms' => $category_id,
                'operator' => 'IN',
            )
        )
    ) );

    return $products_IDs;
}
查看更多
登录 后发表回答