Prafulla Kumar Sahu
Prafulla Kumar Sahu

Reputation: 9693

Getting all product ids of woocommerce categories

I am trying to get all product ids using product_cat here is my code

function get_products_from_category_by_ID( $category ) {

    $products_IDs = new WP_Query( array(
        'post_type' => 'product',
        'post_status' => 'publish',
        'fields' => 'ids',
        'tax_query' => array(
            'relation' => 'AND',
            array(
                'taxonomy' => 'product_cat',
                'field' => 'term_id',
                'terms' => $category,
            )
        ),

    ) );
return $products_IDs;
}

var_dump( get_products_from_category_by_ID( 196 ) );

But getting WP_Query objects instead of ids of products, please let me know what may be the cause ?

Reference :- WooCommerce: function that returns all product ID's in a particular category

Upvotes: 1

Views: 5359

Answers (2)

Rahul Shinde
Rahul Shinde

Reputation: 1662

By using the get_posts wordpress function

Get All WooCommerce Product IDs by Category

In below code only need to add the category name and its work.

$all_ids = get_posts( array(
  'post_type' => 'product',
  'numberposts' => -1,
  'post_status' => 'publish',
  'fields' => 'ids',
  'tax_query' => array(
     array(
        'taxonomy' => 'product_cat',
        'field' => 'slug',
        'terms' => 'your_product_category', /*category name*/
        'operator' => 'IN',
        )
     ),
  ));
  foreach ( $all_ids as $id ) {
     echo $id;
  }

Upvotes: 0

Stanimir Stoyanov
Stanimir Stoyanov

Reputation: 1916

You should return the posts of the query. Wp_Query will always return object, but adding fields parameter to args will only change the posts property. So your code will be:

function get_products_from_category_by_ID( $category ) {

    $products = new WP_Query( array(
        'post_type'   => 'product',
        'post_status' => 'publish',
        'fields'      => 'ids',
        'tax_query'   => array(
            'relation' => 'AND',
            array(
                'taxonomy' => 'product_cat',
                'field'    => 'term_id',
                'terms'    => $category,
            )
        ),

    ) );
    return $products->posts;
}

Upvotes: 1

Related Questions