I18n::with_locale( string $locale, callable $do, TribeEventsarray $args = array() )

Executes a callback ensuring the current_locale will be set to the specified language code.

The method will backup and detach the functions and methods currently filtering the locale filter to execute the callback in isolation and restore the filters after that. The main purpose of this method is to avoid a rat race against plugins and themes that will filter the locale by attaching the filtering method or function at PHP_INT_MAX.


Parameters

$locale

(string) (Required) The locale to set for the execution of the callback.

$do

(callable) (Required) The callable to execute in the context of a specific locale.

$args

(<span class="TribeEventsarray">TribeEventsarray) (Optional) A set of arguments that will be passed to the callback.

Default value: array()


Top ↑

Return

(mixed) The callback return value, if any.


Top ↑

Source

File: src/Tribe/I18n.php

	public function with_locale( $locale, callable $do, array $args = [] ) {
		global $wp_filter;
		// Backup the current state of the locale filter.
		$locale_filters_backup = isset( $wp_filter['locale'] ) ? $wp_filter['locale'] : new \WP_Hook;
		// Set the `locale` filter to a new hook, nothing is hooked to it.
		$wp_filter['locale'] = new \WP_Hook();

		$force_locale = static function () use ( $locale ) {
			return $locale;
		};

		add_filter( 'locale', $force_locale );
		$result = $do( ...$args );
		remove_filter( 'locale', $force_locale );

		$domains = isset( $args[1] ) ? (array) $args[1] : false;
		if ( false !== $domains ) {
			foreach ( $domains as $domain => $file ) {
				// Reload it with the correct language.
				unload_textdomain( $domain );

				if ( 'default' === $domain ) {
					load_default_textdomain();
				} elseif ( is_string( $file ) ) {
					Common::instance()->load_text_domain( $domain, $file );
				}
			}
		}

		// Restore the `locale` filtering functions.
		$wp_filter['locale'] = $locale_filters_backup;

		return $result;
	}

Top ↑

Changelog

Changelog
Version Description
5.4.0 Changed the method visibility to public.
5.1.1 Introduced.