获取woocommerce类别中的所有产品ID
问题描述:
我试图让使用product_cat这里的全部产品ID是我的代码获取woocommerce类别中的所有产品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
答
你应该返回查询的帖子。 Wp_Query将始终返回对象,但将参数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;
}
非常感谢你@Stanimir。 –