skip to Main Content

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.

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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 );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search