Getting all product ids of woocommerce categories

痴心易碎 提交于 2021-02-19 08:16:13

问题


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


回答1:


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



回答2:


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


来源:https://stackoverflow.com/questions/40671239/getting-all-product-ids-of-woocommerce-categories

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!