Php 获取woocommerce类别的所有产品ID
我正在尝试使用product_cat获取所有产品ID这是我的代码Php 获取woocommerce类别的所有产品ID,php,wordpress,woocommerce,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
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_查询对象而不是产品ID,请告诉我可能的原因是什么
参考:-您应该返回查询的帖子。Wp_查询将始终返回object,但将
字段
参数添加到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;
}
通过使用get_postswordpress功能 按类别获取所有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;
}