WordPress comes with a handy auto-download feature for non-installed locale files. But how to implement that in a custom function? Since I needed exactly this (I added an identical select for the locale on another settings page to improve our workflow), I looked for a way to get the exact same behavior.

WordPress has an own file in wp-admin/includes/translation-install.php that represents all functionality to download and install a locale. In my case, whenever I changed the locale setting I could check whether the user is able to install locales, and then install it. The code looks like this:

/**
 * Installs a language.
 * 
 * @param	string	$language The language code
 * @return	bool Whether installation was successful
 */
function prefix_install_language( string $language ): bool {
	if ( ! current_user_can( 'install_languages' ) ) {
		return false;
	}
	
	require_once ABSPATH . 'wp-admin/includes/translation-install.php';
	
	if ( wp_can_install_language_pack() ) {
		return (bool) wp_download_language_pack( $language );
	}
	
	return false;
}
Code language: PHP (php)

wp_download_language_pack already checks whether the locale is already installed. Otherwise it installs it automatically for us.

The $language parameter is always the language code including its country code, e.g. en_US instead of en or de_DE_formal instead of de.

Leave a Reply

Your email address will not be published. Required fields are marked *

To respond on your own website, enter the URL of your response which should contain a link to this post's permalink URL. Your response will then appear (possibly after moderation) on this page. Want to update or remove your response? Update or delete your post and re-enter your post's URL again. (Learn more about webmentions)