Description:
I'm attempting to customize the order of countries in the dropdown menu for the billing address (Billing Country) on the WooCommerce checkout page. To do this, I'm using the woocommerce_checkout_fields filter to adjust the order of countries in the dropdown menu.
The issue arises when I attempt to make these customizations: the dropdown menu for the billing address (Billing Country) works as expected, displaying the countries in the desired order. However, this seems to deactivate the Select2 functionality, which is normally used to provide an enhanced dropdown experience.
My Approach:
Here's an excerpt of my code showcasing the adjustment of country order in the dropdown menu for the billing address:
add_filter( 'woocommerce_checkout_fields', 'customize_country_dropdown_order' );
function customize_country_dropdown_order( $fields ) {
$first_countries = array(
'DE' => 'Germany',
'AT' => 'Austria',
'CH' => 'Switzerland',
);
$rest_countries = array_diff( WC()->countries->get_allowed_countries(), $first_countries );
// Combine the first countries and the rest with a separator
$custom_country_list = array_merge( $first_countries, array( '-' => '------------' ), $rest_countries );
// Update the order of the billing and shipping country dropdowns
$fields['billing']['billing_country']['type'] = 'select';
$fields['billing']['billing_country']['options'] = $custom_country_list;
$fields['shipping']['shipping_country']['type'] = 'select';
$fields['shipping']['shipping_country']['options'] = $custom_country_list;
return $fields;
}
My Question:
How can I reactivate the Select2 functionality for the billing address dropdown menu (Billing Country) after customizing the order of countries? Is there a specific method or approach I can use to achieve this?
You simply need to add the following code snippet to get back jQuery Select2 dropdown:
Note: Here we use selectWoo, the WooCommerce Fork of Select2.
You will get:
Also, you could simplify/compact your code using instead:
New code version (keeps country states sync when changing the country):
Reorder Countries from WooCommerce Checkout Country fields, keeping states sync