I'm trying to create some custom REST API endpoints which get products with some special conditions, for example, one endpoint for featured products.
I tried to use the wc_get_products
function like this:
add_action('rest_api_init', 'my_custom_featured_product_endpoint');
function my_custom_featured_product_endpoint() {
register_rest_route('custom-endpoints/v1', '/products/featured', array(
'methods' => 'GET',
'callback' => 'my_custom_featured_product_callback',
));
}
function my_custom_featured_product_callback() {
$meta_query = WC()->query->get_meta_query();
$tax_query = WC()->query->get_tax_query();
$tax_query[] = array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'featured',
'operator' => 'IN',
);
$args = array(
'tax_query' => $tax_query,
'meta_query' => $meta_query,
);
$result = wc_get_products($args);
return rest_ensure_response($result);
}
The result is just some empty arrays. I can get those products with old fashion get_posts
to replace wc_get_products
but the output format doesn't have some properties like 'price', 'images' ...
So are there any alternatives for wc_get_products
to use for custom REST API endpoints or are there any ways to make it work?
P/S: I tested the query by change the callback function like so:
function my_custom_featured_product_callback() {
$result = wc_get_product(99);//Yes there is a product with ID 99
return rest_ensure_response($result);
}
The result stays the same, just an empty array. So I think the issue must lie with the wc_get_products
and wc_get_product
functions. Maybe the rest_api_init
is not the proper hook for those functions?
$meta_query
and$tax_query
ending up as anyway?rest_api_init
hook, the result is just some empty arrays.WC()->query
. In the REST API WooCommerce won't have run a query.rest_ensure_response()
. You should just be returning the$result
. If you need the posts to match the normal format of returned posts, they need to be prepared.