Woocommerce REST API 扩展订单响应 [英] Woocommerce REST API extending order response

查看:42
本文介绍了Woocommerce REST API 扩展订单响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种方法来扩展 wc-api/vX/orders/响应.我在结账时添加了多个自定义字段(例如:关系编号、交货日期等).这些元数据保存在订单中(wp_postmeta 表).但是为什么它们没有与 api 一起返回?

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?

通常,您可以使用一些代码来扩展 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 );
}

但是当我测试响应(使用 Postman 和 php lib)时,my-website.co/wc-api/v2/orders 自定义元不可见.

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.

有没有办法为 wc-api 注册 api 字段?

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

Tnx!

推荐答案

我有同样的需求,给line_items"添加新值顺序回复

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

我正在使用 wc api v2

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 );

结果封面图片添加到订单项结果

我希望这会在将来对某人有所帮助.

i hope this will help someone in future.

这篇关于Woocommerce REST API 扩展订单响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆