获取所有woocommerce类别的产品ID

时间:2016-11-18 07:06:51

标签: php wordpress woocommerce

我正在尝试使用product_cat获取所有产品ID,这是我的代码

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

但是获取WP_Query对象而不是产品ID,请告诉我可能是什么原因?

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

2 个答案:

答案 0 :(得分:1)

您应该返回查询的帖子。 Wp_Query将始终返回对象,但向args添加fields参数只会更改posts属性。所以你的代码将是:

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

答案 1 :(得分:0)

通过使用 get_posts wordpress函数

按类别获取所有WooCommerce产品ID

在下面的代码中,只需添加类别名称及其工作。

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