Sort countries on WooCommerce Checkout forms

Sometimes you might need to customize the WooCommerce countries lists, mainly if you use a drop-down field to allow customers to choose the country from the list.
In this case, you will need to customize the WooCommerce countries sorting and make the selected countries stay at the top and display first.
How to sort countries on WooCommerce checkout
We can use WooCommerce hooks to filter the country’s data and sort it out in the way we want it to.
In our PHP custom code, we will filter the WooCommerce countries, sorting, and continents. Then we will insert the list of our preferred countries and return the updated countries lists along with the desired countries sorted at the top.
To do so, we need to add code PHP code. The easiest way is to use a child theme and insert the code into the functions.php file. You can also see here how to add custom code snippets in WordPress.
PHP code snippet for sorting countries in WooCommerce
add_filter( 'woocommerce_sort_countries', '__return_false', 999 ); add_filter( 'woocommerce_continents', 'assign_countries_to_continent', 999 ); add_filter( 'woocommerce_countries', 'wc_custom_countries_order', 999, 1 ); function assign_countries_to_continent( $continents ) { $continents['EU']['countries'][] = 'Country1'; $continents['EU']['countries'][] = 'Country2'; $continents['EU']['countries'][] = 'Country3'; $continents['EU']['countries'][] = 'Country4'; $continents['EU']['countries'][] = 'Country5'; return $continents; } function wc_custom_countries_order( $countries ) { $countries = ['Country1' => 'Country 1'] + ['Country2' => 'Country 2'] + ['Country3' => 'Country 3'] + ['Country4' => 'Country 4'] + ['Country5' => 'Country 5'] + $countries; return $countries; }
So, just copy and paste the code from above to your child theme functions.php file. The best place to add the code is at the end of your functions.php file.
Then, start by altering the country names from the example code and add the countries you need to show at the top. Save changes and test your checkout form.
Now, once you click on the country dropdown menu or inside the form field, you will see your top countries displayed first, followed by the rest of the countries.
Conclusion
This should be quite easy to implement, however, we would like to hear your input on this. If you stumble upon any issues, feel free to make your impressions in the comments.