Daniel’s answer was very similar, but applied to plugins rather than themes. For that reason I’ll explain how I specifically did it for themes for anyone else who comes across this problem.
- Create a folder in the root of your theme called “languages”
- Go to https://wpcentral.io/internationalization/, search for your language and copy the “WordPress Locale” code (e.g. cs_CZ for Czech)
- Open Poedit
- File -> New
- Paste the code you coped from wpcentral into the box that appears
- Press save, and save to the “languages” folder you created in step 1
- Press “Extract from sources” (or Catalogue->Properties)
- Under “Sources Paths” press the + on the Paths box
- Select your theme folder (e.g. wp-content/themes/my-theme)
- In the “Sources Keywords” tab, press “New Item”
- Type “__” (underscore underscore, no quotes), and press enter
- Type “_e” (no quotes), and press enter
- Press OK
- Press Save
- Press Catalogue->Update from sources
- You should see all translatable strings from your theme appear (basically any time you use “__( ‘Hello world’, ‘mydomain’ )”, the translation will appear)
- Once you have completed your translations, press File->Compile to MO (save in the same languages folder from step 1)
-
Add the following code to the top of your theme’s functions file:
function mytheme_localisation(){ function mytheme_localised( $locale ) { if ( isset( $_GET['l'] ) ) { return sanitize_key( $_GET['l'] ); } return $locale; } add_filter( 'locale', 'mytheme_localised' ); load_theme_textdomain( 'mytheme', get_template_directory() . '/languages' ); } add_action( 'after_setup_theme', 'mytheme_localisation' );
- Now to dynamically translate your site, you can simply add the URL parameter l={language code} (e.g. mysite.com/?l=cs_CZ – this will load the cs_CZ.mo file that we translated using poedit)
To summarise: to translate strings within your theme, use the following code:
__( 'Hello, World!', 'mytheme' )
Where ‘mytheme’ is the textdomain you set in the function from step 18. Combine this with the creation of the PO/MO files using Poedit and you will be able to make your theme multilingual. In my case this was the perfect solution as I can dynamically change the language using a flag selector on my site, and I can store the user’s preference in a cookie, and redirect them when they arrive back.
I hope this helps someone else who has a similar problem, as this took me ages to figure out.