The code in this article is considered a customisation. As such, it's outside the scope of our support service. Should you need assistance implementing the code, please feel free to contact us to request a consultation.


Adding flags to the dropdown within the country selector widget provided by the Currency Switcher is fairly straightforward, thanks to the Select2 JavaScript library provided by WooCommerce. This article will guide you through the steps to add a flag next to each country.


Important

Before implementing this solution, please consider that showing a flag next to each country will involve loading dozens of image files (one for each country). This can have an impact on the page load speed, as each file has to be fetched separately. This is one of the reasons why the "country flags" feature is not part of the Aelia plugins, out of the box.


1. Find the flag images to upload on your site

Sites like http://flagpedia.net have a database of flags, which you can save and use on your site. Important: before using any image, please make sure that you read the licence that governs its terms of use.


2. Upload the images on your site

Using the Media Manager, add the flags to your site. Take note of the URL of one of the uploaded images. 


If you upload the flags all at the same time, the first part of the URL will be the same for all of them. In this example, the URL of the image file is https://example.org/wp-content/uploads/2018/03/ie.png. We need to take note of the part in bold, as all the images will be in the same folder.


3. Prepare the script that will add the images to the dropdown

The following script will look for the country selector widget on the page and transform it into a Select2 dropdown. Before using it, make sure that you amend the base URL of the country images, using the one from step #2.

/**
 * Runs a JavaScript to add flags to the country options in the dropdown
 * country selector provided by the Aelia Currency Switcher.
 */
add_action('wp_footer', function() {
  ?>
  <script type="text/javascript">
    jQuery(document).ready(function($) {
      /**
       * Adds flags to the options in the dropdown country selector.
       */
      function add_flag_to_country_option(country) {
        if(!country.id) {
          return country.text;
        }

        // Set the base URL for each flag. Replace it with the one from step #2
        var flag_url = 'https://example.org/wp-content/uploads/2018/03';

        var country_code = country.id;
        // Build the URL to each flag image.
        var image_url = flag_url + '/' + country_code.toLowerCase() + '.png';
        // Add the flag to the option list
        var $country_option = $(
          '<span><img src="' + image_url + '" class="aelia-img-flag" /> ' + country.text + '</span>'
        );

        //console.log(country);
        return $country_option;
      }

      // Fix for the [object Object] issue that occurs with some WooCommerce versions
      // @link https://github.com/woocommerce/selectWoo/issues/39
      $.fn.select2.amd.define('customSingleSelectionAdapter', [
        'select2/utils',
        'select2/selection/single',
      ], function (Utils, SingleSelection) {
        const adapter = SingleSelection;
        adapter.prototype.update = function (data) {
          if (data.length === 0) {
            this.clear();
            return;
          }
          var selection = data[0];
          var $rendered = this.$selection.find('.select2-selection__rendered');
          var formatted = this.display(selection, $rendered);
          $rendered.empty().append(formatted);
          $rendered.prop('title', selection.title || selection.text);
        };
        return adapter;
      });  

      // Apply the images to the country options
      $('.widget_wc_aelia_country_selector_widget select').select2({
        templateResult: add_flag_to_country_option,
        templateSelection: add_flag_to_country_option,
        selectionAdapter: $.fn.select2.amd.require('customSingleSelectionAdapter'),
      });
    });
  </script>
  <?php
}, 9999);

/**
 * Loads the Select2 library and CSS on the frontend.
 */
add_action('wp_enqueue_scripts', function() {
  wp_enqueue_script('select2');
  wp_enqueue_style('select2');
});

When ready, you can add the script to your site. See How to Safely Add Custom Code to WordPress Sites for more information on how to do that.


4. Style your new selector

The last step is to adjust the style of your new country selector, so that the flags look nice. Here's a template of the CSS rules for that purpose. You can use it as a starting point, to fine tune the aspect of the selector on your specific site.

/* Set the widget of the country dropdown */
.widget_wc_aelia_country_selector_widget #aelia_cs_currencies {
  width: 100%;
}

/* Style the images, making sure that they are small enough and aligned with the labels */
.select2-container .aelia-img-flag {
  max-width: 30px;
  border-radius: 0;
  display: inline;
  vertical-align: middle;
  margin-top: -3px;
}


You're done! Now the dropdown country selector should show the flags you chose, next to each country, as in the example below.

Should you have any questions, please feel free to contact us. The contact form also provides a convenient way to query our knowledge base, which contains the answers to the most common questions we receive.


You can purchase the Currency Switcher from our online shop.