phpwordpresswoocommercecheckout

How can I enable customer selection on the front-end checkout page in WooCommerce?


I'm running an online store using WooCommerce, and I need to allow store managers or administrators to select an existing customer directly from the front-end while placing an order. Currently, this functionality seems limited to the back-end, but I want it to be available on the checkout page or a custom order form on the front-end.

Key requirements:

My attempts:

*How can I implement this customer selection feature on the front-end? Are there specific plugins or custom code examples that can help achieve this?


Solution

  • 1. Add a Customer Dropdown to the Checkout Page

    // Admin Customer Selection WooCommerce
    function add_customer_selection_field_for_admin()
    {
        if (current_user_can('administrator')) {
            $customers = get_users(array('role__in' => array('customer', 'subscriber')));
            echo '<p class="form-row form-row-wide">';
            echo '<label for="customer_selection">' . __('Select Customer') . '</label>';
            echo '<select required name="customer_selection" id="customer_selection">';
            echo '<option value="">' . __('Select a customer') . '</option>';
    
            foreach ($customers as $customer) {
                echo '<option value="' . esc_attr($customer->ID) . '">' . esc_html($customer->display_name . ' (' . $customer->user_email . ')') . '</option>';
            }
            echo '</select>';
            echo '</p>';
        }
    }
    add_action('woocommerce_before_order_notes', 'add_customer_selection_field_for_admin');
    

    2. Set Checkout Selected Customer to particular order

    function assign_order_to_selected_customer($order_id)
    {
        if (current_user_can('administrator') && isset($_POST['customer_selection']) && !empty($_POST['customer_selection'])) {
            $customer_id = absint($_POST['customer_selection']);
    
            if ($customer_id) {
                update_post_meta($order_id, '_customer_user', $customer_id);
            }
        }
    }
    add_action('woocommerce_checkout_update_order_meta', 'assign_order_to_selected_customer');