Home > Blockchain >  Display product custom field via "woocommerce_email_order_meta" hook in WooCommerce admin
Display product custom field via "woocommerce_email_order_meta" hook in WooCommerce admin

Time:10-14

My products have a custom field called depot. I need to display this field only in admin mail notifications, not to the customer order recap or customer mail notifications.

I use this code to retrieve the custom field in email notifications :

  add_action( 'woocommerce_email_order_meta', 'add_depot', 10, 3 );
  
  function add_depot( $order, $sent_to_admin, $plain_text ){
    $items = $order->get_items();

     foreach ( $items as $item ){
       $depot = $item->get_meta('depot');
       $item['name'] = 'Dépôt: ' . $depot . $item['name'];
     }
  }

At the moment, it displays the field only in customer emails and not in admin emails as I would like. I think I need to use $sent_to_admin but I'm not sure how.

Thank you.

CodePudding user response:

The woocommerce_email_order_meta hook has 4 arguments, via $email->id you can target specific email notifications

So you get:

function action_woocommerce_email_order_meta( $order, $sent_to_admin, $plain_text, $email ) {
    // Targetting specific email notifications
    $email_ids = array( 'new_order' );
    
    // Checks if a value exists in an array
    if ( in_array( $email->id, $email_ids ) ) {
        // Get items
        $items = $order->get_items();

        // Loop trough
        foreach ( $items as $item ) {
            // Get meta
            $depot = $item->get_meta( 'depot' );

            // NOT empty
            if ( ! empty ( $depot ) ) {
               echo '<p style="color:green;font-size:50px;">Dépôt: ' . $depot . ' - ' . $item->get_name() . '</p>';
            } else {
               echo '<p style="color:red;font-size:50px;">Data not found!</p>';
            }
        }
    }
}
add_action( 'woocommerce_email_order_meta', 'action_woocommerce_email_order_meta', 10, 4 );

CodePudding user response:

You can implement this hook:

do_action( 'woocommerce_email_order_meta', $order, $sent_to_admin, $plain_text, $email );

If you see, the second parameter which you get in arguments is - sent to admin. So if that is true, then you can add your custom meta.

Let me know if that helps.

  • Related