Extending Woocommerce API Product Level

Hi all, this post will be about on extending woocommerce API on product level. The goal is to accept new custom fields from API and save the them as the in product post meta. I came across this issue with one of out clients using 3ERP as their partner managing their product. They require an extra field for unique identification from their system. This is completely unrelated to the SKU. Which they also still need to have.
For this we will use the infamous ‘rest_api_init‘ action.

You need to hook a function to this action. In this case, we called it “add_product_custom_data()”. This function called another function ‘register_api_field()‘ which takes 3 parameters. The first one is which endpoint you want to adjust. This could be post, product, or order. The second argument is which field/node you are editing or adding. In this case, we call it ‘custom_field‘. The third parameter is an array of functions. The first one is ‘get_callback‘, this get called when the endpoints GET product is called.  The second one is ‘update_callback‘, this is to handle when you POST or PUT a product.

Handling the GET request

Noe lets see what get function does. It takes 3 parameters, the first one is the OBJECT. From this normally we get the $product->id.  With the id and the $field name, we can decide with data we want to present in the API. In the simplest case, you can return get_post_meta();

Handling the PUT/POST request

Pretty similar to handling the get functions, we received several parameters. The first one is the value that was passed in the API, the second is the $product OBJECT, and the last one in the $field_name where the value is being passed on. We can do simple check if the $value is set or not. If it is then we easily do update_post_meta() then the value is stored in the database. HINT: This will not work on product variation level. If you want to push a custom field to product level, I have written another post for that.

See you guys on the next post!

Leave a Reply