【问题标题】:Getting all product ids of woocommerce categories获取woocommerce类别的所有产品ID
【发布时间】:2017-04-01 23:02:07
【问题描述】:

我正在尝试使用 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

【问题讨论】:

    标签: php wordpress woocommerce


    【解决方案1】:

    您应该返回查询的帖子。 Wp_Query 将始终返回对象,但将 fields 参数添加到 args 只会更改 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;
    }
    

    【讨论】:

      【解决方案2】:

      通过使用 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;
        }
      

      【讨论】:

        猜你喜欢
        • 2016-01-09
        • 1970-01-01
        • 2019-09-03
        • 2015-05-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-20
        相关资源
        最近更新 更多