问题
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 ) );
But getting WP_Query objects instead of ids of products, please let me know what may be the cause ?
Reference :- WooCommerce: function that returns all product ID's in a particular category
回答1:
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;
}
回答2:
By using the get_posts wordpress function
Get All WooCommerce Product IDs by Category
In below code only need to add the category name and its work.
$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;
}
来源:https://stackoverflow.com/questions/40671239/getting-all-product-ids-of-woocommerce-categories