我正在寻找一种扩展 wc-api/vX/orders/ 响应的方法。我在结帐中添加了多个自定义字段(例如:关系编号、交货日期等)。这些元数据保存在订单中(wp_postmeta 表)。但为什么他们没有随 api 返回?
通常您可以使用以下代码扩展 api 响应:
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 自定义元不可见。
有没有办法为 wc-api 注册 api 字段?
Tnx!
我有同样的要求,请在订单响应中为“line_items”添加新值
正在使用 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 );
我希望这对将来的人有帮助。
REST API 挂钩,用于将新值(产品图像)添加到“line_items”,以响应简单产品和可变产品两者
也可用于多种产品
function get_product_order_image( $response, $object, $request ) {
if( empty( $response->data ) )
return $response;
$images = array();
foreach($response->data['line_items'] as $key => $productItems){
$productID = $productItems['product_id'];
$variationID = $productItems['variation_id'];
if($variationID == 0){
$thumbnailID = get_post_meta( $productID, '_thumbnail_id', true);
$attachment = wp_get_attachment_image_src($thumbnailID, 'woocommerce_thumbnail' );
$image = $attachment[0];
}else{
$variation = new WC_Product_Variation( $variationID );
$image_id = $variation->get_image_id();
$attachment = wp_get_attachment_image_src($image_id, 'woocommerce_thumbnail' );
$image = $attachment[0];
}
$response->data['line_items'][$key]['image'] = $image;
}
return $response;
}
add_filter( "woocommerce_rest_prepare_shop_order_object", "get_product_order_image", 10, 3 );
要求:
wp-json/wc/v3/orders
wp-json/wc/v3/orders/XXX
wp-json/wc/v3/orders/?客户=XXX