Change Default Country in WooCommerce Checkout Easily
Explanation
Want to make sure your WooCommerce checkout page always starts with a specific country and state? This little tweak will do just that!
Here's what it does:
- Sets a default country and state for both billing and shipping sections on the checkout page.
- You can choose any country and state by changing the codes in the snippet.
How to use it:
- Find the lines where it says
'US'and'CA'. - Replace
'US'with the country code you want. For example, use'GB'for the United Kingdom. - Replace
'CA'with the state code you want. For example, use'NY'for New York.
Once you've made these changes, your checkout page will automatically show your chosen country and state as the default options. Easy peasy!
Code
1<?php
2/**
3 * Change the default country and state in WooCommerce checkout.
4 *
5 * This function sets the default billing and shipping country and state
6 * for the WooCommerce checkout page.
7 *
8 * @param array $fields The checkout fields.
9 * @return array Modified checkout fields with default country and state.
10 */
11function wp_dudecom_set_default_checkout_country( $fields ) {
12 // Set your desired default country and state
13 $default_country = 'US'; // Change 'US' to your desired country code
14 $default_state = 'CA'; // Change 'CA' to your desired state code
15
16 // Set default billing country and state
17 if ( isset( $fields['billing']['billing_country'] ) ) {
18 $fields['billing']['billing_country']['default'] = $default_country;
19 }
20 if ( isset( $fields['billing']['billing_state'] ) ) {
21 $fields['billing']['billing_state']['default'] = $default_state;
22 }
23
24 // Set default shipping country and state
25 if ( isset( $fields['shipping']['shipping_country'] ) ) {
26 $fields['shipping']['shipping_country']['default'] = $default_country;
27 }
28 if ( isset( $fields['shipping']['shipping_state'] ) ) {
29 $fields['shipping']['shipping_state']['default'] = $default_state;
30 }
31
32 return $fields;
33}
34add_filter( 'woocommerce_checkout_fields', 'wp_dudecom_set_default_checkout_country' );
35?>Instructions
File Location: Add the code to your theme's functions.php file or in a custom plugin file.
Prerequisites:
- Ensure WooCommerce is installed and activated on your WordPress site.
Implementation Steps:
- Access your WordPress admin dashboard.
- Navigate to Appearance > Theme Editor. Alternatively, use an FTP client to access your theme files.
- Locate and open the
functions.phpfile of your active theme. - Copy the provided code snippet.
- Paste the code at the end of the
functions.phpfile. - Modify the
'US'and'CA'values to your desired country and state codes. - Save the changes to the
functions.phpfile. - Visit your WooCommerce checkout page to verify that the default country and state have been updated.
If you need assistance with this implementation or require more advanced functionality, consider reaching out to the experts at wp-dude.com for professional help.