Prafulla Kumar Sahu Prafulla Kumar Sahu - 14 days ago 5
PHP Question

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

Answer

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;
}
Comments