I have a hidden input that I'm populating with some JS on a Woocommerce product screen that I'm trying to access the information on the order metadata that gets sent to the admin screen and admin order notification, but I cannot get access to.
I feel like I can append information to a cart item, but that doesn't come through the final order.
Adding hidden field
function add_polarity_custom_hidden_field() {
global $product;
ob_start(); //Side note...not sure I need Output buffering here, feel free to let me know.
//Here's the input (value is populated with a separate radio group using JS)
?>
<input type="hidden" id="polarity-info" name="polarity_information" value="">
<?php
$content = ob_get_contents();
ob_end_flush();
return $content;
}
add_action('woocommerce_after_variations_table', 'add_polarity_custom_hidden_field', 10);
Which I'm using this function below to add the value of the hidden input to the cart item (Not trying to display this information to the customer)
Adding the custom data to the cart line item:
/**
* Add custom data to Cart
*/
function add_polarity_info_to_order($cart_item_data, $product_id, $variation_id) {
if (isset($_REQUEST['polarity_information'])) {
$cart_item_data['polarity_information'] = sanitize_text_field($_REQUEST['polarity_information']);
}
return $cart_item_data;
}
add_filter('woocommerce_add_cart_item_data', 'add_polarity_info_to_order', 10, 3);
Displaying on the admin page as order metadata:
I'm trying to get that information to display on the
- Order Notification Email as item Metadata
- Admin line items, also as item Metadata
I tried using this function like so, but cannot access the properties I'm looking for:
add_action('woocommerce_admin_order_data_after_order_details', function ($order) {
$order->get_ID();
foreach ($order->get_items() as $item_id => $item) {
$allmeta = $item->get_meta_data();
var_dump($allmeta); //Not within these properties.
}
});
Side Note
I can get the items to display on the cart page using the below code, but I cannot get this to translate to the final order.
/**
* Display information as Meta on Cart page
*/
function add_polarity_data_to_cart_page($item_data, $cart_item) {
if (array_key_exists('polarity_information', $cart_item)) {
$polarity_details = $cart_item['polarity_information'];
$item_data[] = array(
'key' => 'Polarity Information',
'value' => $polarity_details
);
}
return $item_data;
}
add_filter('woocommerce_get_item_data', 'add_polarity_data_to_cart_page', 10, 2);