10

I would like to write my own little plugin for language switching. For that, the very first thing would be to get the rewrite rules running. I have been looking around the web for 2 hours, but I couldn't find an answer to my question yet.

I would like to have it like this: http://www.mysite.com/de/post-title/ or http://www.mysite.com/de/projects/project-title/

So basically, what I'm trying to do is to keep the current url and all it's parameters, just add the currently active language snippet between the site url and the path. Here is my code so far:

function rewrite_rule_de(){
    add_rewrite_tag('%lang%','([^&]+)');
    add_rewrite_rule('^de/(.+?)/?$', 'index.php?p=$matches[1]&lang=de', 'bottom');
    global $wp_rewrite;
    $wp_rewrite->flush_rules();
}
add_action('init', 'rewrite_rule_de');
2
  • 1
    A small hint to this plugin , there does that job, including the rewrite for each language.
    – bueltge
    Apr 1, 2013 at 22:12
  • @rassoh, i am quite interested in learning this kind of plugin development. can you help in this to clear some quick queries on chat SO?
    – Naresh
    Jan 13, 2021 at 9:19

1 Answer 1

12

I got it now , After searched many resources :

function lang_support() {
    return array('en','fr'); // Add your support lang-code (1st place is a default)
}

function rewrite_lang(){
    $langs = lang_support();
    foreach($langs as $lang) {
        add_rewrite_endpoint($lang,EP_PERMALINK|EP_PAGES|EP_ROOT|EP_CATEGORIES);
    }
}
add_action('init','rewrite_lang');

function lang(){
    global $wp_query;
    $langs = lang_support();
    $lang_r = "";
    foreach($langs as $lang) {
        if(isset($wp_query->query_vars[$lang])) {
            $lang_r = $lang;
            $_SESSION['lang'] = $lang_r;
        }
    }
    if(in_array($lang_r,$langs)) {
        return $lang_r;
    } else {
        return $langs[0];
    }
}

function init_session(){session_start();}
add_action('init','init_session',1);

function lang_session() { // Redirect by JS if session is set
    $url_lang= basename($_SERVER['REQUEST_URI']);
    if(!in_array($url_lang,lang_support()) && isset($_SESSION['lang'])) {
        if(!is_404()) {
          wp_redirect(currentURL().$_SESSION['lang'],301);
          exit;
        }
    }
}
add_action('wp_head','lang_session');

function output_buffer() {ob_start();}
add_action('init','output_buffer');

function currentURL() {
    $pageURL=(@$_SERVER["HTTPS"]=="on")?"https://":"http://";
        if($_SERVER["SERVER_PORT"]!="80"){
            $pageURL.=$_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"];
        }else{
            $pageURL.=$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"];
        }
        return $pageURL;
}

Add this code in functions.php. After added code go to wp-admin/options-permalink.php and press Save Changes

So now you can check/use lang code in your template like..

<?php echo lang();?>

or if( lang() === "en" )

Example work urls with my example code :

http://domain.com/ <-- "en"
http://domain.com/en/ <-- "en"
http://domain.com/fr/ <-- "fr"
http://domain.com/es/ <-- "en" (coz , "es" code not set)

http://domain.com/mypage/ <-- "en" (work with "page")
http://domain.com/mypage/fr/ <-- "fr"
http://domain.com/mypage/es/ <-- "en" (coz , "es" code not set)

http://domain.com/mypost/ <-- "en" (work with "post")
http://domain.com/mypost/fr/ <-- "fr"
http://domain.com/mypost/es/ <-- "en" (coz , "es" code not set)

Better idea / bug fixer / found error + bug ? https://gist.github.com/l2aelba/5244912

3
  • 1
    Well, the plain functions with such generic names will quickly bring up conflicts. Should be prefixed or wrapped up in a pseudo namespace (class). And for a more safe check for SSL check this gist.
    – kaiser
    Apr 2, 2013 at 1:04
  • 3
    This is great, thanks a lot l2aelba! While I will try it out like this, the more „classic“ approach would be to have the language code always in front of the rest of the link, e.g. [home_url][lang][mypost] or „domain.com/en/mypage“. Any ideas on how to accomplish this?
    – rassoh
    Apr 28, 2013 at 23:13
  • Very old but still totally valid. As @rassoh I prefer the original domain.com/lang/slug format so i'll try again with add_rewrite_rule that seems to allow that
    – cdsaenz
    Mar 2, 2022 at 20:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.