Using WordPress ‘load_textdomain’ PHP action

The load_textdomain WordPress action fires before the MO translation file is loaded.

Usage

add_action('load_textdomain', 'your_custom_function', 10, 2);

function your_custom_function($domain, $mofile) {
  // your custom code here
}

Parameters

  • $domain (string) – Text domain, unique identifier for retrieving translated strings.
  • $mofile (string) – Path to the .mo file.

More information

See WordPress Developer Resources: load_textdomain

Examples

Load a custom MO file

Replace the default MO file with a custom one from your theme directory.

add_action('load_textdomain', 'load_custom_mo_file', 10, 2);

function load_custom_mo_file($domain, $mofile) {
  // Check if the domain matches your text domain
  if ($domain == 'your-text-domain') {
    // Set the custom MO file path in your theme directory
    $mofile = get_template_directory() . '/languages/custom-' . $domain . '.mo';
  }
  return $mofile;
}

Modify MO file path

Change the MO file path for a specific text domain.

add_action('load_textdomain', 'change_mo_file_path', 10, 2);

function change_mo_file_path($domain, $mofile) {
  if ($domain == 'your-text-domain') {
    $mofile = '/new/path/to/your-' . $domain . '.mo';
  }
  return $mofile;
}

Log MO file loading

Log each MO file loaded by WordPress.

add_action('load_textdomain', 'log_mo_file_loading', 10, 2);

function log_mo_file_loading($domain, $mofile) {
  error_log('Loading MO file: ' . $mofile . ' for domain: ' . $domain);
}

Load additional MO files

Load additional MO files for a specific text domain.

add_action('load_textdomain', 'load_additional_mo_files', 10, 2);

function load_additional_mo_files($domain, $mofile) {
  if ($domain == 'your-text-domain') {
    $additional_mofile = get_template_directory() . '/languages/additional-' . $domain . '.mo';
    load_textdomain($domain, $additional_mofile);
  }
}

Skip loading MO file for a specific text domain

Prevent loading the MO file for a specific text domain.

add_action('load_textdomain', 'skip_loading_mo_file', 10, 2);

function skip_loading_mo_file($domain, $mofile) {
  if ($domain == 'skip-this-domain') {
    // Return an empty string to skip loading the MO file
    return '';
  }
  return $mofile;
}