获取woocommerce类别的所有产品ID [英] Getting all product ids of woocommerce categories

查看:36
本文介绍了获取woocommerce类别的所有产品ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

参考:- WooCommerce:功能返回特定类别中的所有产品 ID

推荐答案

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

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

这篇关于获取woocommerce类别的所有产品ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆