Woocommerce REST API extending order response

I’m looking for a way to extend the wc-api/vX/orders/ reponse. I’ve added multiple custom fields to the checkout (for eg: relation number, delivery date etc). These meta are saved within the order (wp_postmeta table). But why are they not returned with the api?

Normally you can extend the api response with some code like:

add_action( 'rest_api_init', 'custom_register_api_fields' );

function custom_register_api_fields() {
    register_rest_field( 'shop_order','relation_number',
    array(
        'get_callback'    => 'custom_api_meta_callback',
        'update_callback' => null,
        'schema'          => null,
    )
    );
}

/**
*
* @param array $object Details of current post.
* @param string $field_name Name of field.
* @param WP_REST_Request $request Current request
*
* @return mixed
*/

function custom_api_meta_callback( $object, $field_name, $request ) {
 return get_post_meta( $object[ 'id' ], $field_name, true );
}

But when I test the response (with Postman and the php lib), my-website.co/wc-api/v2/orders the custom meta are not visible.

Is there a way to register api fields for the wc-api?

Tnx!

Answer

i have the same requirement, add new value to “line_items” in order response

am using wc api v2

https://website.com/wp-json/wc/v2/orders

function get_product_order_image( $response, $object, $request ) {
 
    if( empty( $response->data ) )
        return $response;
    $order_pid= $response->data['line_items'][0]['product_id'];
     $l_w_product_meta = get_post_meta($response->data['line_items'][0]['product_id']);
    $order_imgUrl= wp_get_attachment_url( $l_w_product_meta['_thumbnail_id'][0], 'full' );

    $response->data['line_items'][0]['cover_image'] = $order_imgUrl;
 
    return $response;
} 

add_filter( "woocommerce_rest_prepare_shop_order_object", array( $this, "get_product_order_image"), 10, 3 );

Result cover image added to line item result

i hope this will help someone in future.

Leave a Reply

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