Using WordPress ‘load_textdomain()’ PHP function

The load_textdomain() WordPress PHP function loads a .mo file into the text domain $domain.

Usage

load_textdomain( $domain, $mofile, $locale = null )

Input:

load_textdomain( 'my-text-domain', 'path/to/my-text-domain.mo', 'es_ES' );

Output: The .mo file is loaded into the text domain ‘my-text-domain’ with the Spanish locale.

Parameters

  • $domain (string) – Required. Text domain. Unique identifier for retrieving translated strings.
  • $mofile (string) – Required. Path to the .mo file.
  • $locale (string) – Optional. Locale. Default is the current locale. Default: null.

More information

See WordPress Developer Resources: load_textdomain

Examples

Load custom text domain

Load a custom text domain for your plugin or theme.

Explanation: This code loads the .mo file from the languages folder of your plugin or theme with the current locale.

function myplugin_load_textdomain() {
  $domain = 'my-plugin';
  $mofile = plugin_dir_path( __FILE__ ) . 'languages/' . $domain . '-' . get_locale() . '.mo';
  load_textdomain( $domain, $mofile );
}
add_action( 'init', 'myplugin_load_textdomain' );

Load different locale

Load a specific locale for the text domain, different from the current user locale.

Explanation: This code first checks if the text domain is already loaded. If it is, it unloads the text domain and then loads the text domain with the specified locale.

function myplugin_load_specific_locale() {
  $domain = 'my-plugin';
  $locale = 'fr_FR';

  if ( is_textdomain_loaded( $domain ) ) {
    unload_textdomain( $domain );
  }

  $mofile = plugin_dir_path( __FILE__ ) . 'languages/' . $domain . '-' . $locale . '.mo';
  load_textdomain( $domain, $mofile );
}
add_action( 'init', 'myplugin_load_specific_locale' );

Load text domain from theme

Load a text domain for a theme.

Explanation: This code loads the .mo file from the languages folder of your theme with the current locale.

function mytheme_load_textdomain() {
  $domain = 'my-theme';
  $mofile = get_template_directory() . '/languages/' . $domain . '-' . get_locale() . '.mo';
  load_textdomain( $domain, $mofile );
}
add_action( 'after_setup_theme', 'mytheme_load_textdomain' );

Load text domain from child theme

Load a text domain for a child theme.

Explanation: This code loads the .mo file from the languages folder of your child theme with the current locale.

function mychildtheme_load_textdomain() {
  $domain = 'my-child-theme';
  $mofile = get_stylesheet_directory() . '/languages/' . $domain . '-' . get_locale() . '.mo';
  load_textdomain( $domain, $mofile );
}
add_action( 'after_setup_theme', 'mychildtheme_load_textdomain' );