How to Make Your WordPress Theme or Plugin Translation-Ready

Make a WordPress theme or plugin translation-ready

A theme or plugin is translation-ready when every text the user sees goes through one of the WordPress i18n functions with the theme’s or plugin’s text domain. Then a translator only creates .po/.mo files, and nobody has to touch the code.

Problem: The strings of a theme or plugin are written directly in the code and cannot be translated.

Solution: Wrap the strings in __(), _e(), esc_html__() and the related functions with your text domain, load the text domain, and generate a .pot file for translators.

The functions

<?php
// Return a translated string
$label = __( 'Read more', 'textdomain' );

// Print it, escaped for HTML or for an attribute
esc_html_e( 'Submit', 'textdomain' );
?>
<input type="search" placeholder="<?php esc_attr_e( 'Search...', 'textdomain' ); ?>">
<?php

// Singular and plural
printf(
    esc_html( _n( '%d comment', '%d comments', $count, 'textdomain' ) ),
    $count
);

// Same word, different meaning: add a context for translators
$status = _x( 'Draft', 'post status', 'textdomain' );

The text domain must be a plain string, not a variable or a constant: the tools that extract strings read the code, they do not run it.

Loading the text domain

<?php
// Theme: functions.php
add_action( 'after_setup_theme', function () {
    load_theme_textdomain( 'textdomain', get_template_directory() . '/languages' );
} );

// Plugin: the main plugin file
add_action( 'plugins_loaded', function () {
    load_plugin_textdomain( 'textdomain', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
} );

The .pot file

The .pot file is the list of all strings that translators start from. WP-CLI creates it from the code:

wp i18n make-pot . languages/textdomain.pot --domain=textdomain

Translators open it in Poedit (or translate on translate.wordpress.org for themes and plugins in the official directory) and save textdomain-de_DE.po and .mo into the languages folder.

Sentences with variables

Never build a sentence from translated pieces: word order differs between languages. Use one string with numbered placeholders, so the translator can change their order, and add a comment for translators:

<?php
/* translators: 1: author name, 2: date */
printf( esc_html__( 'Posted by %1$s on %2$s', 'textdomain' ), esc_html( $author ), esc_html( $date ) );

NOTE: Do not put HTML or URLs into translated strings unless they are part of the sentence; keep markup outside and pass links as placeholders. A translator can break HTML, and every changed URL would invalidate all translations of the string.