我正在尝试使用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,请让我知道可能是什么原因?
您应该返回查询的帖子。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;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句