Custom multilingual themes
This guide will show you how to create multilingual WordPress themes. A multilingual theme is more than just wrapping all the texts in GetText calls and providing a .mo file. Localizing the theme’s texts is one major step, but there are other things that have to be done.
A theme for a multilingual site needs to show available languages, allow selecting which language to view in and display correctly in each language.
These are the things that we’ll need to do:
- Providing localization for different languages.
- Allowing users to switch from one language to the other.
- Returning the right content per language.
- Telling WPML what needs translation.
In order for the theme to display in different languages, the texts need to pass translation before they are displayed. WordPress uses GetText for this and so should your theme.
We’ve written a post about localizing WordPress themes. It tells how to wrap the theme’s texts in GetText calls, create translations (.mo files) and apply them to the theme.
A language switcher shows visitors which languages are available and lets them choose.
Language switchers can come in different forms. Some people prefer a compact drop down menu with language names. Others display country flags and others show horizontal or vertical lists of languages.
WPML makes implementing language switchers easy. It comes built in with its own drop-down language switcher which can also be included as a widget. This language switcher can display country flags, language names and their translations. It can be configured from the WPML->Languages menu.
You can also create your own custom language switcher and insert to different places in the theme. The custom language switcher manual page explains how you can create it and provides examples for common uses. Adding a custom language switcher to your theme can add flare and elegance and make it obvious to users that the theme is intended for multilingual sites.
Many themes include hard-coded link to pages, categories and tags.
WPML hooks to the standard WordPress API functions and filters them by language.
For example, when you call:
$args = array( 'category' => 1 );
$myposts = get_posts( $args );
Supposing category “1″ is an English category and the translation to Spanish is category “4″. When view a Spanish page and run this code, WPML will replace the category number in the filter to “4″.
For this to happen, your code must use only WordPress API calls and not manually query the database (which is a bad practice by itself).
You can control this functionality in WPML->Languages. Look for the option to automatically adjust IDs.
WPML can read a language configuration file. This file tells it everything it needs to know about your theme.
This includes admin texts, custom fields and custom types you’re using.
Once you create this XML file, WPML will auto configure and allow users to run a multilingual site without clicking on a single setting screen.