How to develop a multilingual theme?

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.

  1. Create a folder in the root of your theme called “languages”
  2. Go to https://wpcentral.io/internationalization/, search for your language and copy the “WordPress Locale” code (e.g. cs_CZ for Czech)
  3. Open Poedit
  4. File -> New
  5. Paste the code you coped from wpcentral into the box that appears
  6. Press save, and save to the “languages” folder you created in step 1
  7. Press “Extract from sources” (or Catalogue->Properties)
  8. Under “Sources Paths” press the + on the Paths box
  9. Select your theme folder (e.g. wp-content/themes/my-theme)
  10. In the “Sources Keywords” tab, press “New Item”
  11. Type “__” (underscore underscore, no quotes), and press enter
  12. Type “_e” (no quotes), and press enter
  13. Press OK
  14. Press Save
  15. Press Catalogue->Update from sources
  16. You should see all translatable strings from your theme appear (basically any time you use “__( ‘Hello world’, ‘mydomain’ )”, the translation will appear)
  17. Once you have completed your translations, press File->Compile to MO (save in the same languages folder from step 1)
  18. 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' );
    
  19. 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.

Leave a Comment