Automatic language redirect for WordPress, WiX and others

Automatic language redirect for WordPress, WiX and others
Some AI generated world map with arrows in between 🙈

I've worked on a few sites where they have sub folders for various languages and some sort of plugin, that would redirect visitors to the correct language when visiting the front page of the site. On multiple occasions people have come to me and said it wasn't working properly, so we disabled the plugin and I wrote the following code instead, to be included in the header:

<script type="text/javascript">
  if (window.location.pathname == "/" && !sessionStorage.redirectedOnce)
  {
    // Assuming that the page at / is the frontpage

    // Danish
    if ( navigator.language.startsWith("da") )
    {
      window.location.pathname = "/da";
      sessionStorage.redirectedOnce = '1';
    }
    // French
    if ( navigator.language.startsWith("fr") )
    {
      window.location.pathname = "/fr";
      sessionStorage.redirectedOnce = '1';
    }
    // Polish
    if ( navigator.language.startsWith("pl") )
    {
      window.location.pathname = "/pl";
      sessionStorage.redirectedOnce = '1';
    }
  }
</script>

All it does is redirect people to a specific folder depending on their language and does nothing if their language is English. It only redirects once per session.

Instead of looking at their IP and guessing at their language, it just looks at the language set in their browser. If it's good enough for the browser, it might just be good enough for your website.