The context sensitive Language Versions link
Most bilingual sites only have a fixed link to the other language version. Wherever you are on one language version of a site, clicking on the Language Version link always takes you to the home page of the other version of the site. But I want my visitors get the exact page they are viewing written in the other language. For example, if my visitor is visiting
http://dallascao.com/en/2009/07/the-context-sensitive-language-versions-link/
by clicking “中文” at the bottom, he is taken to
http://dallascao.com/cn/2009/07/the-context-sensitive-language-versions-link/
So it involves replacing the “/en/” the URL of the current page with “/cn/”.
The following php code gives out wrong results:
<?php $url_old = "http://".$_SERVER ['HTTP_HOST'].$_SERVER['PHP_SELF']; ?> <?php $url_new=str_replace("en","cn",$url_old); ?> <a href=<?php echo $url_new; ?>Chinese</a>
Whichever page you are visiting, $url_old always gives the home URL “/en/index.php”. This is because I turned Permalinks on and the URL is rewritten. The URL rewritting takes place after the execution of PHP codes on the server side, and therefore the php string “$url_old” cannot get the actual URL as it is rewritten afterwards. The following java script can get the right current URL as java script runs on the client’s computer:
<script> var s=window.location.href r=s.replace (/en/, "cn"); document.write ("<li><a title='English verion of this page' href="+r+">Chinese</a></li>") </script>
More information:
Did you enjoy this post? Why not leave a comment below and continue the conversation, or subscribe to my feed and get articles like this delivered automatically to your feed reader.
Twitter
Email
RSS