Add ACF user data to Woocommerce Orders as metadata

44 Views Asked by At

For local delivery we've added routenumbers and -locations to our users, so we can calculate the best route for local delivery. In Woocommerce and we're using Advanced Order Export Pro to create an export of the orders based on the shipping method.

By default the custom fields aren't coming back in the order details, so we're looking for a solution to add the routenumber and -locations to the order details based on e-mailaddress (or something).

Custom field on user-level should be added to order details

enter image description here

Does anyone know how we can fix this?

We've searched on the internet and thought we can fix this we a plugin like Checkout field editor, add those fields and make them invisible on the front-end. But I'm looking for some code to put in the functions.php.

1

There are 1 best solutions below

0
LoicTheAztec On

Use the following, to add ACF User custom data to the order as custom order metadata:

// When order is placed in checkout, add ACF user fields as custom order meta data
add_action( 'woocommerce_checkout_create_order', 'add_order_total_weight_metadata' );
function add_order_total_weight_metadata( $order ) {
    $user_id = (int) get_current_user_id(); // Get user ID

    if ( $user_id > 0 ) {
        // First ACF user field
        if( $route_number = get_field("routenumber", "user_{$user_id}" ) ) {
            $order->add_meta_data('route_number', $route_number);
        }
        // 2nd ACF user field
        if( $route_location = get_field("routelocatie", "user_{$user_id}" ) ) {
            $order->add_meta_data('route_location', $route_location);
        }
    }
}

Code goes in functions.php file of your child theme (or in a plugin). It should work.

The order custom meta_keys to be used in Advanced Order Export Pro are:

  • route_number for Routenumber
  • route_location for Routelocatie

To get those custom field values from the order object use:

$routenumber  = $order->get_meta('route_number');
$routelocatie = $order->get_meta('route_location');

Related: ACF - How to Get Values From a User