Search code examples
localizationinternationalizationwpml

localize a window.location.href


I am writing a 404 custom page and all is good, but I am using WPML and therefore I am localizing my strings.

This i part of my code:

<h4><?php _e('You still can\'t find anything?', 'kslang'); ?></h4>
<h5><?php _e('Well, then you probably should give us a wake up call...', 'kslang'); "\n"?></h5>
<h5><?php _e('but be aware who you\'re waking up!', 'kslang');?></h5>
<h5><?php _e('You\'re sure? Well, then...', 'kslang'); ?></h5>
<form>
    <input type="button" value="<?php _e('Contact Us!', 'kslang'); ?>" onClick="window.location.href='http://example.com/contact-us-today'">
</form>
<h5><?php _e('or try the Site Map Below. You\'re also welcome to check out our related projects!', 'kslang'); ?></h5>

Now the issue is, that my

"window.location.href='http://example.com/contact-us-today'"

is not redirecting to the relative language.

I though I could simply wrap the href link in get text, like by button text and the rest of the strings.

this doesn't work, obviously the matter is more complicated. Do I need to use a if/else statement?

Has anybody a idea how to redirect to the correct language? (I tried to use _e with the idea to translate the href link in String translator, but this doesn't work with _e because inserting the php snippet breaks my site in this case)

Hope somebody can give a input...


Solution

  • to redirect to the appropriate language version using window.location.href, you need to include the language in your URL... i.e, for French, redirect to "http://www.example.com/fr/contact-us-today" (with "fr" after the domain). You can do this dynamically by detecting the current WPML language in PHP and echoing it as a JavaScript variable, like this:

    //Get current WPML language
    global $sitepress;
    $language = $sitepress->get_current_language();
    //Echo as JS variable
    echo "<script>var lang = '".$language."';</script>"
    

    Then, you can redirect like this:

    window.location.href='http://www.example.com/'+lang+'/contact-us-today';
    

    NOTE: This example assumes you are using language folders for your different languages. You will need to adjust accordingly if you are using subdomains or a language query parameter.