Many new content management systems have inbuilt mechanisms for managing and toggling between content in multiple languages. Unfortunately, a CMS may be serious overkill for most smaller sites, yet they still need to serve their few pages in more than one language. Here's a simple way to allow for this.
I make it a general rule to make separate files for my header (including navigation) and footer files, and simply include them on all pages within my site. That way if I need to make a change, I make it in one place, such as header.php. This method also makes it very easy to provide a link to alternate languages.
How it works
So let's say you want to provide content in English and Spanish. You have the following pages:
1. index.php
2. about.php
3. contact.php
All 3 of them include header.php and footer.php. All you need to do is create a copy of each file, with the language short form as an extension. (index_es.php, about_es.php, etc). Same with the header/footer files.
Now, at the top of the English header, we'll place the language option, providing a link to the same page in English or Spanish. The beauty of this is that we don't have to program the link on each page, we can use PHP to dynamically determine it at run-time. Here's how:
<?php
global $title;
$this_page = $_SERVER['SCRIPT_NAME'];
$en_ext = ".php"; // the extension for English pages
$es_ext = "_es.php"; // the extension for Spanish pages
$new_link = str_replace($en_ext, $es_ext, $this_page); //reverse this to go back to English from a Spanish page
?>
Now here's the code to output the link. I included the logic to not provide a Spanish link in the support section, because support is a web app that's only in English.
<div id="languages">
English
<?php if(!is_string(strstr($this_page, "/support/"))) { ?>
| <a href="<?php echo($new_link); ?>">Italian</a>
<?php } ?>
</div>
Sign up for our daily email newsletter:
You must log in to post a comment.