determine_locale()WP 5.0.0

Gets the current site locale (site language, ex, en_US) desired for the request.

  • On front-pages return the result of get_locale() function.
  • On admin-pages return the result of get_user_locale() function.
  • For REST (JSON) request return the result of get_user_locale() function, if GET parameter contains ?_locale=user.
  • On wp-login.php page — you can change the locale by setting wp_lang GET parameter, for example, ?wp_lang=ru_RU.

This new function is a wrapper for smart usage of both functions: get_locale() and get_user_locale().

1 time — 0.000001 sec (speed of light) | 50000 times — 0.09 sec (speed of light) | PHP 7.2.5, WP 5.0
Hooks from the function

Return

String. The determined locale. Ex: ru_RU.

Usage

determine_locale();

Examples

0

#1 What the function returns

echo determine_locale();
// display 'ru_RU', for russian site
0

#2 The example of translation file load

add_action( 'plugins_loaded', 'load_my_textdomain' );
function load_my_textdomain(){
	$mo_file_path = dirname(__FILE__) . '/lang/'. determine_locale() . '.mo';
	load_textdomain( 'mytexdomain', $mo_file_path );
}

Notes

  • Global. String. $pagenow The filename of the current screen.

Changelog

Since 5.0.0 Introduced.

determine_locale() code WP 6.5.2

function determine_locale() {
	/**
	 * Filters the locale for the current request prior to the default determination process.
	 *
	 * Using this filter allows to override the default logic, effectively short-circuiting the function.
	 *
	 * @since 5.0.0
	 *
	 * @param string|null $locale The locale to return and short-circuit. Default null.
	 */
	$determined_locale = apply_filters( 'pre_determine_locale', null );

	if ( $determined_locale && is_string( $determined_locale ) ) {
		return $determined_locale;
	}

	if (
		isset( $GLOBALS['pagenow'] ) && 'wp-login.php' === $GLOBALS['pagenow'] &&
		( ! empty( $_GET['wp_lang'] ) || ! empty( $_COOKIE['wp_lang'] ) )
	) {
		if ( ! empty( $_GET['wp_lang'] ) ) {
			$determined_locale = sanitize_locale_name( $_GET['wp_lang'] );
		} else {
			$determined_locale = sanitize_locale_name( $_COOKIE['wp_lang'] );
		}
	} elseif (
		is_admin() ||
		( isset( $_GET['_locale'] ) && 'user' === $_GET['_locale'] && wp_is_json_request() )
	) {
		$determined_locale = get_user_locale();
	} elseif (
		( ! empty( $_REQUEST['language'] ) || isset( $GLOBALS['wp_local_package'] ) )
		&& wp_installing()
	) {
		if ( ! empty( $_REQUEST['language'] ) ) {
			$determined_locale = sanitize_locale_name( $_REQUEST['language'] );
		} else {
			$determined_locale = $GLOBALS['wp_local_package'];
		}
	}

	if ( ! $determined_locale ) {
		$determined_locale = get_locale();
	}

	/**
	 * Filters the locale for the current request.
	 *
	 * @since 5.0.0
	 *
	 * @param string $determined_locale The locale.
	 */
	return apply_filters( 'determine_locale', $determined_locale );
}