我正在寻找一种扩展way /vX/orders/ reponse的方法。我在结帐中添加了多个自定义字段(例如:关系号、交付日期等)。这些元被保存在订单中(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库)时,我的-website.co/wc/v2/orders定制的元数据是不可见的。
有办法为wc注册api字段吗?
Tnx!
发布于 2018-12-11 14:25:09
我有同样的要求,在"line_items“中添加新的值,以便响应
am使用wc 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 );我希望这能对将来的人有所帮助。
发布于 2021-03-02 14:02:36
REST钩子用于将新值(产品映像)添加到"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/命令
wp-json/wc/v3/order/XXX
wp-json/wc/v3/orders/?customers=XXX
https://stackoverflow.com/questions/40802219
复制相似问题