如何提取WooCommerce订单项非唯一元键的指定元数据
Grouping WooCommerce 3 Order Item Meta Data by Non-Unique Keys
I see you're working with WooCommerce 3 order items and need to group their meta data by shared keys like Carboidrato, Proteína, and Guarnição. Let's adjust your existing code to achieve this cleanly, while avoiding direct access to protected properties (best practice for WooCommerce development).
Modified Code with Grouping Logic
// Get the $order object from an ID (if needed) $order = wc_get_order( $order_id ); // Initialize an empty array to store grouped meta data $grouped_meta = []; // Loop through each order line item foreach( $order->get_items() as $item ){ // Fetch all item meta data (including hidden entries) $item_meta = $item->get_meta_data(); // Loop through each meta entry to organize by key foreach( $item_meta as $meta ){ // Get key and value using WC_Meta_Data's public methods $meta_key = $meta->get_key(); $meta_value = $meta->get_value(); // Create or append to the group for this key if( !isset( $grouped_meta[ $meta_key ] ) ){ $grouped_meta[ $meta_key ] = []; } $grouped_meta[ $meta_key ][] = $meta_value; } } // Display the grouped output (for testing) echo '<pre>'; print_r( $grouped_meta ); echo '</pre>';
How This Works
- Initialization: We start with an empty
$grouped_metaarray to hold our organized data. - Fetch Meta Data: Using
get_meta_data()gives usWC_Meta_Dataobjects, and we use their public methods (get_key()andget_value()) to safely access the data without touching protected properties. - Grouping: For each meta entry, we check if the key already exists in our grouped array. If not, we create a new array for it; then we append the value to that group.
Example Output
Your grouped data will look like this, making it easy to access all values for each category:
Array ( [Carboidrato] => Array ( [0] => Arroz Branco COM Feijão [1] => Arroz Integral à Grega COM Feijão [2] => Macarrão Alho Poró ) [Proteína] => Array ( [0] => Parmegiana Bovina [1] => Parmegiana Frango ) [Guarnição] => Array ( [0] => Batata Rosthi Recheada com Requeijão [1] => Farofa ) )
Alternative: Using Formatted Meta Data
If you prefer to work with the get_formatted_meta_data() output (stdClass objects), you can adjust the inner loop like this:
foreach( $item->get_formatted_meta_data( '_', true ) as $meta ){ $meta_key = $meta->key; $meta_value = $meta->value; if( !isset( $grouped_meta[ $meta_key ] ) ){ $grouped_meta[ $meta_key ] = []; } $grouped_meta[ $meta_key ][] = $meta_value; }
内容的提问来源于stack exchange,提问作者vrec
相关产品推荐
相关产品推荐

