Search code examples
phpwoocommercecustom-fieldsordersuser-roles

Add a user-role as custom meta data to WooCommerce orders


In WooCommerce I am wondering if it's possible to save the user role as a custom field to the order (custom meta data) using user_role meta key, like in this screenshot:

enter image description here

Any help is welcome.


Solution

  • The following will add the user roles as custom order meta data:

    // Add the user roles as order meta data
    add_action( 'woocommerce_checkout_create_order', 'add_user_roles_to_order_meta_data', 10, 2 );
    function add_user_roles_to_order_meta_data( $order, $data ) {
        if( $order->get_user_id() > 0 ) {
            $user = $order->get_user();
            $user_role = reset($user->roles)
    
            $order->update_meta_data( 'user_role', $user_role );
        }
    }
    

    Code goes in function.php file of your active child theme (or active theme). Tested and works.

    To get the user role from the WC_Order Object $order variable you will use:

    $user_role = $order->get_meta('user_role');
    

    Or from the order Id $order_id variable:

    $user_role = get_post_meta($order_id, 'user_role', true);