WooCommerce API, add custom data to default endpoints

A lot of exciting things happened with the release of WooCommerce 2.6! Of of the most important is a completely new REST API based on the WordPress REST API infrastructure.

To be honest, WooCommerce already had is own powerful and stable API (now called legacy API) rolled out months ago because of high demand, but after the release of WordPress official API infrastructure in version 4.4, they integrated with the official WP API (which makes a lot of sense, especially in a long-term vision).

If you are interested in understanding what is changed, you can take a look here, but in this post, I will only cover how to add custom data to default endpoints.

A very common scenario is to add additional data to products read (get) queries. With the legacy API (< WooCommerce 2.6) you could use the woocommerce_api_product_response filter:

This filter and everything from Legacy API is still available and will work as expected even if you have the last version go WooCommerce, but if you are moving to the new WooCommerce API endpoints, that filter is no longer available.

You can instead use woocommerce_rest_prepare_{$this->post_type}, so in this case woocommerce_rest_prepare_product.

I personally take a lot of advantage using API filters, especially when I need to include “extensions added” data (eg. WC Product Add-ons) to API response.

Until next time,
Francesco