I am using Woocommerce latest version 3.4.2. How can I get some order item metadata and assign them a custom value?
- I get meta data with a common array
$item_product_data_array
. - I need to get a certain value - (Additional modification for the product). And assign custom sku.
Example: I have coffe - sku 1001, in array - key [0] Product coffe have additional modification - sugar (meta data) Need found "Sugar" and assign him custom sku - 50005.
[label] => Optionally select [value] => Array ( [0] => Cinnamon [1] => Sugar [2] => Mint )
That is, this additive should be in one cycle as a price or quantity. All of them must treat their product with a value [0].
// Get product details
$items = $order->get_items();
$sku = array();
$product_kol = array();
$product_price = array();
$item_product_meta_data_array = array();
foreach( $items as $key => $item){
$product_kol[] = $item['qty'];
$product_price[] = $item['line_total'];
$item_id = $item['product_id'];
$product = wc_get_product($item_id);
$sku[] = $product->get_sku();
$items_meta_data[] = $item->get_meta_data();
$meta_data1 = $item->get_meta('Sugar');
if( ! empty( $meta_data1 ) ) {
$skus[] = "50005";
$item_quantities[] = "1";
}
}
// Product details for sending as one line to an external service
foreach ($sku as $key => $value){
$data .= "&product[".$key."]=".$value."";
$data .= "&product_kol[".$key."]=".$product_kol[$key]."";
$data .= "&product_price[".$key."]=".$product_price[$key]."";
if(isset($product_mod[$key])) {
$data .= "&product_mod[".$key."]=".$product_mod[$key]."";
}
}
I think this will be useful stuff, since all the modules of additional options to the product add all the values to the meta data. And it is difficult to pull them out and include them in the desired cycle.
So, we should get:
//products sku
$product[0] = "10000"; // Coffe
$product[1] = "10001"; // Juice - second product for axample
$product[2] = "50005"; // Sugar
//products quantity
$product_kol[0] = "1"; // Аmount of coffee
$product_kol[1] = "1"; // Аmount of juice
$product_kol[2] = "1"; // Аmount of sugar
//Modifiers if they exist
$product_mod[2] = "0"; //The product with key 2 is the product modifier with key 0