Translate PHP strings in WP-CLI custom command

When you switch languages using WPML API in the WP-CLI command callback, the strings are not translated. Please see wpmlsupp-9941 for more details.

You can workaround this by adding this code to a plugin or custom plugin but not a theme.

if (defined('WP_CLI') && WP_CLI) {
		add_filter('locale', function ($locale) {
			$command = $GLOBALS['argv'][1] ?? false;
			$lang = $GLOBALS['argv'][2] ?? false;

			if ('WPMLTest' === $command && !empty($lang)) {
				global $sitepress;
				$lang = method_exists($sitepress, 'get_locale_from_language_code') ? $sitepress->get_locale_from_language_code($lang) : $lang;
				return $lang;
			}

			return $locale;
		});
}

Make sure to replace WPMLTest with your command name.

Then run the command like this wp WPMLTest es where es language code in which you want to load the strings.
Your custom command callback will not need to switch the language using WPML API. The above function will change the locale using language parameter passed in the command line argument.

Please make sure you add your ticket to track the number of requests.


Support Thread Example

Let us know if this snippet is not working for you:

This snippet doesn’t work
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments