Search code examples
phpwordpresswoocommercehook-woocommerceorders

Display custom meta data in WooCommerce admin order after billing address


After having read the answer from 7uc1f3r on Add a select field with time intervals based on opening, closing and breaks times in WooCommerce checkout I did my best to understand how to add the actual time to the order.

This was already mentioned in the initial question, but when modifying that code to match the answer code by 7uc1f3r I get a notice on the order page (admin).

It says:

Notice: id was called incorrectly. Order properties should not be accessed directly. Backtrace: require('wp-admin/edit-form-advanced.php'), do_meta_boxes, WC_Meta_Box_Order_Data::output, do_action('woocommerce_admin_order_data_after_billing_address'), WP_Hook->do_action, WP_Hook->apply_filters, wps_select_checkout_field_display_admin_order_meta, WC_Abstract_Legacy_Order->__get, wc_doing_it_wrong Please see Debugging in WordPress for more information. (This message was added in version 3.0.) in /wp-includes/functions.php on line 5311

The actual delivery time shows, but with this notice above.

That said; I did my best in modifying the code further to check "if" delivery time is not blank and if so, show it. That did not help either - the notice is still there.

This is what I changed the code into:

add_action('woocommerce_admin_order_data_after_billing_address', 'wps_select_checkout_field_display_admin_order_meta', 10, 1 );
function wps_select_checkout_field_display_admin_order_meta( $order ) {
    
    if ( get_post_meta( $order->get_id(), 'delivery_time' != '' ) ) {
    
        echo '<p><strong>'.__('Requested Delivery Time').':</strong> ' . get_post_meta($order->id, 'delivery_time', true) . '</p>';
    }
}

Not sure how to get rid of the notice.


Solution

  • The problem comes from $order->id, so try the following instead:

    add_action('woocommerce_admin_order_data_after_billing_address', 'wps_select_checkout_field_display_admin_order_meta', 10, 1 );
    function wps_select_checkout_field_display_admin_order_meta( $order ) {
        $delivery_time = $order->get_meta('delivery_time');
        
        if ( ! empty($delivery_time) ) {
            echo '<p><strong>'.__('Requested Delivery Time').':</strong> ' . $delivery_time . '</p>';
        }
    }
    

    Now it should work.