问题
I'm building custom endpoint using Woocommerce Products and the query return 6 objects but empty don't now why is that? what I'm missing on my code below?
Code
add_action('rest_api_init', function () {
register_rest_route( 'hash', 'related-products',array(
'methods' => 'GET',
'callback' => 'hash_realated_products'
));
});
function hash_realated_products() {
// Get 10 most recent product IDs in date descending order.
$query = new WC_Product_Query( array(
'limit' => 6,
'status' => 'publish',
'orderby' => 'rand',
'tax_query' => array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => '257,352' 'operator' => 'IN'
)
) );
$products = $query->get_products();
return $products;
}
回答1:
The problem was I didn't call for the data from the products array!
so the final code will be :
$products_query = $query->get_products();
$products = array();
foreach ( $products_query as $product ) {
$products[] = $product->get_data();
}
return $products;
来源:https://stackoverflow.com/questions/59361618/woocommerce-get-products-return-empty-objects