Using WordPress ‘load_textdomain_mofile’ PHP filter

The load_textdomain_mofile WordPress PHP Filter allows you to modify the MO file path for loading translations for a specific text domain.

Usage

add_filter('load_textdomain_mofile', 'my_custom_load_textdomain_mofile', 10, 2);

function my_custom_load_textdomain_mofile($mofile, $domain) {
    // your custom code here
    return $mofile;
}

Parameters

  • $mofile (string): Path to the MO file.
  • $domain (string): Text domain. Unique identifier for retrieving translated strings.

More information

See WordPress Developer Resources: load_textdomain_mofile

Examples

Change MO File Path

Modify the MO file path to load translations from a custom location.

add_filter('load_textdomain_mofile', 'change_mo_file_path', 10, 2);

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

Load Different MO File Based on User Language

Load a different MO file depending on the user’s language preference.

add_filter('load_textdomain_mofile', 'load_user_language_mo_file', 10, 2);

function load_user_language_mo_file($mofile, $domain) {
    if ('my-text-domain' === $domain) {
        $language = get_user_meta(get_current_user_id(), 'language', true);
        $mofile = '/path/to/your/mo/files/' . $language . '.mo';
    }
    return $mofile;
}

Rename Text Domain

Rename the text domain to load translations with a different domain.

add_filter('load_textdomain_mofile', 'rename_text_domain', 10, 2);

function rename_text_domain($mofile, $domain) {
    if ('old-text-domain' === $domain) {
        $mofile = str_replace('old-text-domain', 'new-text-domain', $mofile);
    }
    return $mofile;
}

Load Plugin Translations from Theme Directory

Load translations for a plugin from the active theme’s directory instead of the plugin’s directory.

add_filter('load_textdomain_mofile', 'load_plugin_translations_from_theme', 10, 2);

function load_plugin_translations_from_theme($mofile, $domain) {
    if ('plugin-text-domain' === $domain) {
        $mofile = get_stylesheet_directory() . '/languages/plugin-text-domain.mo';
    }
    return $mofile;
}

Check MO File Existence

Check if the MO file exists before loading it, and fall back to the default language if it doesn’t.

add_filter('load_textdomain_mofile', 'check_mo_file_existence', 10, 2);

function check_mo_file_existence($mofile, $domain) {
    if (!file_exists($mofile) && 'my-text-domain' === $domain) {
        $mofile = '/path/to/your/default/mo/file.mo';
    }
    return $mofile;
}