Filter out unwanted order item meta data from Woocommerce email notifications

前端 未结 4 1836
悲哀的现实
悲哀的现实 2021-01-20 17:20

In the order email templates (for example email-order-items.php), WooCommerce uses the function wc_display_item_meta to display product details in

4条回答
  •  悲哀的现实
    2021-01-20 18:02

    I hear, that you want to show the Order Item Meta Data in the admin backend only. That's actually a tricky one. I have played around for some hours but no solution I have found, guarentee that the Order Itema Meta Data doesn't show up in e-mails to the customer.

    The thing is that there are several ways these e-mails are fired (eg. through the resend meta box (which @rtpHarry mentions) or by changing order status either at the order overview, the single order view or an automatic/programmatically order status change). That gives many cases where it's neccessary to unset the Order Item Meta Data - you need to find all cases except the admin backend.

    Therefore, my suggestion is to first completely remove the Order Item Meta Data using the above mentioned woocommerce_order_item_get_formatted_meta_data filter and then add them again using an action like woocommerce_before_order_itemmeta which ONLY fires in the admin backend. Because the Order Item Meta Data is unset you cannot use the get_formatted_meta_data method to get the data. Instead you can use the function wc_get_order_item_meta.

    Complete code (tested and works):

    //Hide 'Qty Selector', 'Qty' and 'Total' completely
    add_filter( 'woocommerce_order_item_get_formatted_meta_data', 'unset_specific_order_item_meta_data');
    function unset_specific_order_item_meta_data($formatted_meta){
        foreach( $formatted_meta as $key => $meta ){
            if( in_array( $meta->key, array('Qty Selector', 'Qty', 'Total') ) )
                unset($formatted_meta[$key]);
        }
        
        return $formatted_meta;
    }
    
    //Add 'Qty Selector', 'Qty' and 'Total' in the admin backend only
    add_action('woocommerce_before_order_itemmeta', 'add_specific_order_item_meta_data_in_backend', 10, 2);
    function add_specific_order_item_meta_data_in_backend( $item_id, $item ) {
        //Only applies for line items
        if( $item->get_type() !== 'line_item' ) return;
        
        $qty_sel_lines = wc_get_order_item_meta($item_id, 'Qty Selector', false);
        $qty_lines = wc_get_order_item_meta($item_id, 'Qty', false);
        $total_lines = wc_get_order_item_meta($item_id, 'Total', false);
        
        foreach ($qty_sel_lines as $qty_sel_line){
            echo $qty_sel_line . '
    '; } foreach ($qty_lines as $qty_line){ echo $qty_line . '
    '; } foreach ($total_lines as $total_line){ echo $total_line. '
    '; } }

    Note: If you need to add the Order Item Meta Data to the admin e-mails, you need to do that seperately. I have not examined the options on that.

提交回复
热议问题