Country Selector - Featured Image

How to develop your own country selection page on WordPress

When building a WordPress site that serves users from different countries, creating a country selection page can significantly enhance user experience. This guide will walk you through developing a country selection page using JavaScript, explaining key concepts like Immediately Invoked Function Expressions (IIFE) and cookies.

Using JavaScript IIFE for country redirection allows the redirection to be handled on the client side, ensuring that the website’s share previews and initial load show the actual content rather than the country selection page, unlike PHP, a server-side language, which would process the redirection before the page is loaded, potentially affecting share previews and initial page views.

Step-by-Step Guide to Creating a Country Selection Page

1. Setting Up JavaScript for Country Selection

The following JavaScript code manages country selection on your WordPress site. Save this script in your child theme’s inc folder as country-selection.js.

var ukWebsite = "https://website.com/uk";
var unitedKingdom = "/uk";
var sriLankan = "/";
var sriLankanWebsite = "https://website.com";

// JavaScript code on your country selection page
document.addEventListener("click", function (event) {
  if (event.target.classList.contains("select-country")) {
    var country = event.target.getAttribute("data-country");
    document.cookie =
      "country=" +
      country +
      "; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/; priority=high;";
    // Redirect the user to the appropriate website based on their selection
    // Get the query string part of the current URL
    var queryString = window.location.search;

    // Create a URLSearchParams object to parse the query string
    var urlParams = new URLSearchParams(queryString);

    // Access the value of the "redirect" parameter
    var redirectValue = urlParams.get("redirect");
    if (redirectValue && redirectValue.length > 0) {
      window.location.href =
        country === "uk"
          ? ukWebsite + "/" + redirectValue.replace(unitedKingdom, "")
          : sriLankanWebsite + "/" + redirectValue.replace(unitedKingdom, "");
    } else {
      window.location.href =
        country === "uk" ? ukWebsite + "/" : sriLankanWebsite + "/";
    }
  }
});

(function () {
  function checkCountrySelection() {
    var currentURL =
      window.location.protocol +
      "//" +
      window.location.host +
      window.location.pathname;

    if (isPage("country-selection")) {
      // Do nothing on the country selection page
      return;
    }

    var countryCookie = getCookie("country");

    if (countryCookie) {
      var country = countryCookie;

      if (
        currentURL.startsWith(sriLankanWebsite) &&
        !currentURL.startsWith(ukWebsite)
      ) {
        if (country === "lk") {
          return;
        } else {
          if (
            window.location.pathname.startsWith(unitedKingdom) &&
            country === "lk"
          ) {
            window.location.href =
              sriLankanWebsite + window.location.pathname.substring(3);
          } else if (country === "uk") {
            window.location.href = ukWebsite + window.location.pathname;
          } else {
            window.location.href = sriLankanWebsite + window.location.pathname;
          }
        }
      } else if (currentURL.startsWith(ukWebsite) && country === "uk") {
        // User is on the "uk" site, and the cookie matches, so return
        return;
      } else {
        if (country === "lk") {
          if (window.location.pathname.startsWith(unitedKingdom)) {
            window.location.href =
              sriLankanWebsite + window.location.pathname.substring(3);
          } else {
            window.location.href = sriLankanWebsite + window.location.pathname;
          }
        } else if (country === "uk") {
          window.location.href = ukWebsite + window.location.pathname;
        }
      }
    } else {
      window.location.href =
        siteURL() + "/country-selection?redirect=" + window.location.pathname;
    }
  }

  function isPage(pageName) {
    return window.location.pathname.includes(pageName);
  }

  function getCookie(cookieName) {
    var name = cookieName + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var cookieArray = decodedCookie.split(";");
    for (var i = 0; i < cookieArray.length; i++) {
      var cookie = cookieArray[i];
      while (cookie.charAt(0) === " ") {
        cookie = cookie.substring(1);
      }
      if (cookie.indexOf(name) === 0) {
        return cookie.substring(name.length, cookie.length);
      }
    }
    return "";
  }

  function siteURL() {
    return window.location.protocol + "//" + window.location.host;
  }

  checkCountrySelection();
})();

You can access this code on my GitHub by clicking here.

2. Enqueue the JavaScript in Your Child Theme

To ensure the script is loaded on your WordPress site, add the following code to your child theme’s functions.php file:

<?php

function country_selection_script() {
    wp_enqueue_script('country-selection-script', get_stylesheet_directory_uri() . '/inc/country-selection.js', array('jquery'), '1.0', false);
}

add_action('wp_enqueue_scripts', 'country_selection_script');

You can access this code as well on my GitHub by clicking here.

3. Adding Country Selection Buttons

Create a new page on both sites where you are hoping to show the country selection code and add buttons to your HTML where users can select their country. Each button should have an data-country attribute like so:

<button class="select-country" data-country="lk">Sri Lanka</button>
<button class="select-country" data-country="uk">United Kingdom</button>

You can use a page builder like Elementor, Divi, or WP Bakery to design a neat page but make sure the buttons have the data-country attribute or else the code wouldn’t work.

Understanding Key Concepts

Immediately Invoked Function Expressions (IIFE)

An Immediately Invoked Function Expression (IIFE) is a function that runs as soon as it is defined. It has two main parts:

  1. Function Expression: This defines the function within parentheses.
  2. Immediately Invoked: This part () executes the function immediately.

In the code:

(function() {
    // Your code here
})();

This construct helps in avoiding global scope pollution by enclosing the code within a function scope.

Cookies

Cookies are small pieces of data stored on the user’s device by the browser. They are used to remember information about the user between requests. In the provided code, cookies are used to store the selected country:

document.cookie = "country=" + country + "; expires=Fri, 31 Dec 9999 23:59:59 GMT; path=/; priority=high;";

The getCookie function retrieves the value of the specified cookie:

function getCookie(cookieName) {
    var name = cookieName + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var cookieArray = decodedCookie.split(';');
    for (var i = 0; i < cookieArray.length; i++) {
        var cookie = cookieArray[i];
        while (cookie.charAt(0) === ' ') {
            cookie = cookie.substring(1);
        }
        if (cookie.indexOf(name) === 0) {
            return cookie.substring(name.length, cookie.length);
        }
    }
    return "";
}

Creating a country selection page on your WordPress site involves setting up a JavaScript file to manage the user’s selection and redirecting them based on their choice. The above code ideally works in a WordPress setup where you have two sites in a multisite network that use the same theme, however, you can tweak the above code if you have the websites using different themes and if you have multiple sites as separate WordPress installation.

Understanding IIFEs and cookies is crucial in this process. By following the steps outlined above, you can implement a user-friendly country selection feature, enhancing the experience for visitors from different regions.


Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

Share via
Copy link