Using WordPress ‘load_theme_textdomain()’ PHP function

The load_theme_textdomain() WordPress PHP function loads the theme’s translated strings.

Usage

load_theme_textdomain( $domain, $path );
load_theme_textdomain('my_theme', get_template_directory() . '/languages');

Parameters

  • $domain (string) – Text domain. Unique identifier for retrieving translated strings.
  • $path (string|false) – Optional. Path to the directory containing the .mo file. Default: false.

More information

See WordPress Developer Resources: load_theme_textdomain()

Examples

Basic Usage

Load translations for my_theme. The .mo files must use language-only filenames, like languages/de_DE.mo in your theme directory.

add_action('after_setup_theme', 'my_theme_setup');

function my_theme_setup(){
    load_theme_textdomain('my_theme', get_template_directory() . '/languages');
}

Switch Theme Language using URL Parameter

Switch theme language using a variable passed within the URL, for example, to load the Tamazikht language, your URL would look like; www.example.com/?l=tz_MA. This will search for a .mo file named tz_MA.mo in the language directory inside your theme.

add_filter( 'locale', 'my_theme_localized' );

function my_theme_localized( $locale ) {
    if ( isset( $_GET['l'] ) ) {
        return sanitize_key( $_GET['l'] );
    }
    return $locale;
}

load_theme_textdomain( 'my_theme_textdomain', get_template_directory().'/languages' );

Child Theme Translation

Load translations for my_child_theme in a child theme.

add_action('after_setup_theme', 'my_child_theme_setup');

function my_child_theme_setup(){
    load_theme_textdomain('my_child_theme', get_stylesheet_directory() . '/languages');
}

Fallback to Parent Theme Translation

Load translations for my_child_theme in a child theme, and fallback to the parent theme’s translations if the child theme’s translations are not available.

add_action('after_setup_theme', 'my_child_theme_setup');

function my_child_theme_setup(){
    load_theme_textdomain('my_child_theme', get_stylesheet_directory() . '/languages');
    load_theme_textdomain('my_parent_theme', get_template_directory() . '/languages');
}

Custom Text Domain Path

Load translations for my_theme from a custom path.

add_action('after_setup_theme', 'my_theme_setup');

function my_theme_setup(){
    load_theme_textdomain('my_theme', get_template_directory() . '/custom/languages');
}