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?

3 s
3

you missed something, when you get a product using wc_get_product it returns to you an abstract object, so if you need to get product do this

$product =  wc_get_product($product_id);
return $product->get_data();

also you can use all the other functionalities too, such as:

$product->get_status();
$product->get_gallery_image_ids();
...

Leave a Reply

Your email address will not be published. Required fields are marked *