Search code examples
phpwordpresswoocommerceadvanced-custom-fieldsorders

Display ACF order custom field in WooCommerce orders


Need to add a field to the WooCommerce order details page where I can add a tracking number in the order page to be displayed for the customer.

I have added ACF to the order-details.php template as below, but it does not display. When I inspect page element all I can see is <h2></h2>. This is my current ACF code:

<h2><?php the_field('tracking_number'); ?></h2>

Solution

  • You can use the following to dis

    // Display tracking information as a row on order totals everywhere
    add_filter( 'woocommerce_get_order_item_totals', 'order_item_totals_tracking_row', 1000, 3 );
    function order_item_totals_tracking_row( $total_rows, $order, $tax_display ){
        if( $tracking_number  = get_field('tracking_number', $order->get_id()) ) {
            $new_total_rows   = []; // Initializing
            $has_tracking_row = false; // Initializing
            $tracking_row     = array( // tracking information array
                'label' => __("Tracking number", "woocommerce"),
                'value' => $tracking_number
            );
    
    
            // Loop through order total rows
            foreach( $total_rows as $key => $values ) {
                $new_total_rows[$key] = $values;
                // Inserting tracking information array
                if( $key === 'shipping' ) {
                    $new_total_rows['tracking'] = $tracking_row;
                    $has_tracking_row = true;
                } elseif( $key === 'payment_method' && ! $has_tracking_row ) {
                    $new_total_rows['tracking'] = $tracking_row;
                }
            }
            return $new_total_rows;
        }
    
        return $total_rows;
    }
    

    Code goes in functions.php file of the active child theme (or active theme). It should works.