Adding a default country and state to the checkout page

If you are just starting out, you may not have a very wide reach, you may not have any international orders, and you might not even have orders from outside your state or province. If that's the case, why make people type it in? With a touch of code, we can set some defaults that will help people get through the checkout process.

How to do it…

This code can either go in your theme's functions.php file or in a custom WooCommerce plugin. Let's take a look at the following steps:

  1. Open either your theme's functions.php file or a custom plugin file.
  2. We'll start by setting just the default country. At the bottom of the file, add the following code:
    add_filter( 'default_checkout_country', 'woocommerce_cookbook_default_checkout_country' ); 
    // change the default country to USA function 
    woocommerce_cookbook_default_checkout_country() { 
        return 'US'; 
    }
  3. If you also want to set a default state, you'll have to add a bit more code. In the following code sample, I'll set the default state to Colorado:
    add_filter( 'default_checkout_state', 'woocommerce_cookbook_default_checkout_state' ); 
    // change the default state to Colorado 
    function woocommerce_cookbook_default_checkout_state() { 
        return 'CO'; 
    }

    Note

    If you want to change the default country to something other than the US, you'll have to find out the country's two-letter code. A Google search will uncover this. If you want to change the default state to something other than Colorado, you'll have to replace the two-letter state code of Colorado, CO, to your state code.

  4. Save the file and upload it to your site.

Make sure you're logged out of your site, add a product to your cart, and proceed to check out. You should see the state and country filled in by default.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset