I am trying to make a custom order page where I can display all orders details to the front end.
I have created a product with custom fields. Now i am trying to display the metadata of the order but I want to select certain values from the array.
Here is my code:
$args = array('status'=> 'on-hold');
$orders = wc_get_orders($args);
foreach ( $orders as $order ) {
$order_id = $order->get_id();
$order_items = wc_get_order($order_id);
//echo $order_items;
foreach( $order_items->get_items() as $item ){
$item_data = $item->get_data();
$item_meta_data = $item->get_meta_data();
$formatted_meta_data = $item->get_formatted_meta_data( '_', true );
//echo '<pre>' . print_r($item_meta_data, true) . '</pre>';
echo '<pre>' . print_r($formatted_meta_data, true) . '</pre>';
}
}
Here is what I am getting :
Array
(
[45] => stdClass Object
(
[key] => Characters
[value] => Character1 ($29.00)
Character2 ($29.00)
[display_key] => Characters
[display_value] =>
Character1 ($29.00)
Character2 ($29.00)
)
[46] => stdClass Object
(
[key] => More
[value] => Card ($40.00)
Bounties ($15.00)
[display_key] => More
[display_value] =>
Card ($40.00)
Bounties ($15.00)
)
)
//etc
What I am trying to do is getting something like this:
Character1 ($29.00)
Character2 ($29.00)
Card ($40.00)
Bounties ($15.00)
You can use the WC_Date method get_meta() from your desired meya keys as follows:
// Get orders
$orders = wc_get_orders( array( 'status'=> 'on-hold', 'limit' => -1 ) );
// Loop through the array of WC_Order Objects
foreach ( $orders as $order ) {
// Get order Id
$order_id = $order->get_id();
// Loop through order items
foreach( $order->get_items() as $item ) {
// Get "Characters" item custom field
$characters = $item->get_meta('Characters');
if ( $characters ) {
echo '<p>Characters: ' . $characters . '</p>'; // Display
}
// Get "More" item custom field
$more = $item->get_meta('More');
if ( $more ) {
echo '<p>More: ' . $more . '</p>'; // Display
}
}
}
It should work