How to edit wordpress woocommerce order api responses (legacy + latest)

<?php
//// FOR LEGACY API ONLY

add_filter('woocommerce_api_order_response', 'harsh_add_shipping_phone_legacy', 99, 1);
function harsh_add_shipping_phone($order_data)
{
    $order_data["billing_address"]["email"] = "XXXX";
	$shipping_phone = get_post_meta($order_data["id"],"_shipping_phone",1);
	if($shipping_phone!==false && strlen($shipping_phone))
	{
		$order_data["billing_address"]["biller_phone"] = $order_data["billing_address"]["phone"];
		$order_data["shipping_address"]["phone"] = $shipping_phone;
		$order_data["billing_address"]["phone"] = $shipping_phone;
	}
	foreach($order_data["line_items"] as $k=>$v)
	{
		unset($order_data["line_items"][$k]["meta"]);
	}
    return $order_data;
}


//// FOR latest api

function wc_add_rest_order_meta( $response, $post, $request ) {

	$order_data = $response->get_data();
    $order_data["billing"]["email"] = "XXXX";
   $sp = array_search('_shipping_phone', array_column($order_data["meta_data"], 'key'));
   if($sp!==false)
   {
     $order_data["billing"]["biller_phone"] = $order_data["billing"]["phone"];
     if(strlen($order_data["meta_data"][$sp]->value))
     {
     $order_data["shipping"]["phone"] = $order_data["meta_data"][$sp]->value;
     $order_data["billing"]["phone"] = $order_data["meta_data"][$sp]->value;
     }
   }
	foreach($order_data["line_items"] as $k=>$v)
	{
		unset($order_data["line_items"][$k]["meta_data"]);
	}
	
	$response->data = $order_data;

	return $response;	
}
function wc_add_rest_order_meta2( $response, $post, $request ) {
foreach($response as $oneorder)
{
	$order_data = $oneorder->get_data();
    $order_data["billing"]["email"] = "XXXX";
   $sp = array_search('_shipping_phone', array_column($order_data["meta_data"], 'key'));
   if($sp!==false)
   {
     $order_data["billing"]["biller_phone"] = $order_data["billing"]["phone"];
     if(strlen($order_data["meta_data"][$sp]->value))
     {
     $order_data["shipping"]["phone"] = $order_data["meta_data"][$sp]->value;
     $order_data["billing"]["phone"] = $order_data["meta_data"][$sp]->value;
     }
   }
	foreach($order_data["line_items"] as $k=>$v)
	{
		unset($order_data["line_items"][$k]["meta_data"]);
	}
	
	$oneorder->data = $order_data;

}
	
	return $response;	
}
add_filter( 'woocommerce_rest_prepare_shop_order_object', 'wc_add_rest_order_meta', 10, 3 );
add_filter( 'woocommerce_rest_prepare_shop_orders_object', 'wc_add_rest_order_meta2', 10, 3 );

Posted

in

,

by

Tags:

Comments

Leave a Reply

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