skip to Main Content

I am creating a script for a WordPress Multisite, to allow the user to switch between sites i.e. EN, FR, DE.

The link in the menu is structured as so:

<li class="en-link">
<a href="https://example.com" />EN</a>
</li>
<li class="fr-link">
<a href="https://example.com/fr" />FR</a>
</li>

I’d like the user to be able to switch back and forth between these sites. But this does not work for subpages obviously. So i need to be able to get everything infront of the first forward slash and apply it to these links.

This is what i have currently:

jQuery(function ($) {
var currentURL = (document.URL); 
var part = currentURL.split("/")[1];
$(".en-link a").attr('href', $(".en-link a").attr('href') + part);
$(".fr-link a").attr('href', $(".fr-link a").attr('href') + part); 
});

But to no avail. Any thoughts?

2

Answers


  1. Chosen as BEST ANSWER

    This is what worked for me using jQuery

    $(document).ready(function () {
    var trail = window.location.href.substr(window.location.href.lastIndexOf("/")+1); 
    $(".en-link").find('a').attr('href', $(".en-link").find('a').attr('href') + trail);
    $(".fr-link").find('a').attr('href', $(".fr-link").find('a').attr('href') + trail); 
      }); 
    

    But also need to counter for subpages for press and media sections:

    jQuery(function ($) {
      $(document).ready(function () {
    var trail = window.location.href.substr(window.location.href.lastIndexOf("/")+1);  
      var trailSub = window.location.href.substr(window.location.href.lastIndexOf("/")-5);  
        if (window.location.href.indexOf("press") != -1) {
    $(".en-link").find('a').attr('href', $(".en-link").find('a').attr('href') + trailSub);
    $(".fr-link").find('a').attr('href', $(".fr-link").find('a').attr('href') + trailSub); 
        }
        else if (window.location.href.indexOf("media") != -1) {
    $(".en-link").find('a').attr('href', $(".en-link").find('a').attr('href') + trailSub);
    $(".fr-link").find('a').attr('href', $(".fr-link").find('a').attr('href') + trailSub); 
        }
        else {
          $(".en-link").find('a').attr('href', $(".en-link").find('a').attr('href') + trail);
    $(".fr-link").find('a').attr('href', $(".fr-link").find('a').attr('href') + trail); 
        }
      });
    });
    

    im sure this can be simplified, but have minified for now.


  2. You can get the path from JavaScript’s built-in Location, window.location.pathname.split('/')[1] will give you the first segment of the path, depending on your url this will be either "fr", "de" or "en"

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search