Skip to content

Instantly share code, notes, and snippets.

@bekarice
Created December 28, 2016 20:18
Show Gist options
  • Save bekarice/f1ba5b8e2f3c62d82a5cbc100dc3e1ad to your computer and use it in GitHub Desktop.
Save bekarice/f1ba5b8e2f3c62d82a5cbc100dc3e1ad to your computer and use it in GitHub Desktop.
Example: Add order item meta to WC REST API
<?php // only copy if needed
/**
* Example: Add order meta to the REST API
* WC 2.6+
*
* @param \WP_REST_Response $response The response object.
* @param \WP_Post $post Post object.
* @param \WP_REST_Request $request Request object.
* @return object updated response object
*/
function wc_add_rest_order_meta( $response, $post, $request ) {
$order_data = $response->get_data();
foreach ( $order_data['line_items'] as $key => $item ) {
$order_data['line_items'][ $key ]['metakey'] = wc_get_order_item_meta( $item['id'], '_meta_value_key', true );
}
$response->data = $order_data;
return $response;
}
add_filter( 'woocommerce_rest_prepare_shop_order', 'wc_add_rest_order_meta', 10, 3 );
@filipfilipovich
Copy link

Thanks a lot, spared me a lot of headache I've been having last couple of days. 😄

@androidcode33
Copy link

Hi everyone, there's a couple changes you'll need to make to get this working with the latest version of the API:

In my code I used get_post_meta for the item, you can change that to whatever you like.

add_filter( 'woocommerce_rest_prepare_shop_order_object', 'my_wc_prepare_shop_order', 10, 3 );

function my_wc_prepare_shop_order( $response, $object, $request ) {
$order_data = $response->get_data();

foreach ( $order_data['line_items'] as $key => $item ) {
$order_data['line_items'][ $key ]['mykey'] = get_post_meta( $item['product_id'], 'mykeyname', true );
}

$response->data = $order_data;
return $response;
}

this worked for me. thanks

@DannyChuro22
Copy link

I'm trying to add that code into my function.php file but I can't get the product attribute values ​​from the order detail API to come out, can you please help me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment