H
H
Heretic Man2020-06-10 08:58:20
WooCommerce
Heretic Man, 2020-06-10 08:58:20

Modifying responses in woocommerce rest api?

When rest request /wc/v3/productsthrows out a huge json file with unnecessary fields.

How to make certain fields missing in the response from the server? Through functions.php or maybe something needs to be written in the request itself?

Something like this arrives:
1*AgDkQLVcZg8bMwsa5dcyww.png

But I want something like this:
1*02ten7KnGoXcaLw9DKa2hg.png

Answer the question

In order to leave comments, you need to log in

2 answer(s)
H
Heretic Man, 2020-06-10
@heretic_man

in functions.php

add_filter( 'woocommerce_rest_prepare_product_object', 'filter_function_name', 10, 3 );
function filter_function_name( $response, $object, $request ){
    if( empty( $response->data ) )
        return $response;

    $inclde = [
        'id'        => $response->data['id'],
        'name'      => $response->data['name'],
        'images'    => $response->data['images'],
        'price'     => $response->data['price'],
        'meta_data' => $response->data['meta_data'],
        'categories'=> $response->data['categories']
    ];

    return $inclde;
}

WooCommerce has these preparatory filters for most of its API responses. Note that their format is woocommerce_rest_prepare_{$type} where $type is the post type or taxonomy name (e.g. product_cat). In WooCommerce 2.7, some of these filters also have the _object suffix.
You can make rest requests adaptive using the third parameter ($request) in the function and manipulate the response ($response).
Thanks Alex for the tip!

A
Alex, 2020-06-10
@Kozack

Alternatively, try rest_prepare_{$this->post_type}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question