WooCommerce: Can’t use wc_get_products for custom REST API endpoints

Question

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 a empty array. So I think the issue must lies with the wc_get_products and wc_get_product functions. Maybe the rest_api_init is not the properly hook for those functions ?

0
, , , , david lee 2 years 2020-01-01T08:38:22-05:00 0 Answers 215 views 0

Leave an answer

Browse
Browse