From 6048eb34be4df5414641de439564608b23f83d93 Mon Sep 17 00:00:00 2001 From: Pascal Birchler Date: Fri, 16 Jun 2023 12:56:03 +0000 Subject: [PATCH] I18N: Allow to short-circuit `load_textdomain()`. Introduces a new `pre_load_textdomain` filter, which is useful for plugins to develop and test alternative loading/caching strategies for translations. This brings consistency with the existing `pre_load_script_translations` filter for JavaScript translations. Props ocean90, swissspidy. Fixes #58035. git-svn-id: https://develop.svn.wordpress.org/trunk@55928 602fd350-edb4-49c9-b593-d223f7449a82 --- src/wp-includes/l10n.php | 22 +++++++++++++++++++++ tests/phpunit/tests/l10n/loadTextdomain.php | 16 +++++++++++++++ 2 files changed, 38 insertions(+) diff --git a/src/wp-includes/l10n.php b/src/wp-includes/l10n.php index a0c7bba903..9467a6b19c 100644 --- a/src/wp-includes/l10n.php +++ b/src/wp-includes/l10n.php @@ -717,6 +717,28 @@ function load_textdomain( $domain, $mofile, $locale = null ) { $l10n_unloaded = (array) $l10n_unloaded; + /** + * Filters whether to short-circuit loading .mo file. + * + * Returning a non-null value from the filter will effectively short-circuit + * the loading, returning the passed value instead. + * + * @since 6.3.0 + * + * @param bool|null $loaded The result of loading a .mo file. Default null. + * @param string $domain Text domain. Unique identifier for retrieving translated strings. + * @param string $mofile Path to the MO file. + * @param string|null $locale Locale. + */ + $loaded = apply_filters( 'pre_load_textdomain', null, $domain, $mofile, $locale ); + if ( null !== $loaded ) { + if ( true === $loaded ) { + unset( $l10n_unloaded[ $domain ] ); + } + + return $loaded; + } + /** * Filters whether to override the .mo file loading. * diff --git a/tests/phpunit/tests/l10n/loadTextdomain.php b/tests/phpunit/tests/l10n/loadTextdomain.php index 26e567d663..234e98015a 100644 --- a/tests/phpunit/tests/l10n/loadTextdomain.php +++ b/tests/phpunit/tests/l10n/loadTextdomain.php @@ -300,4 +300,20 @@ class Tests_L10n_LoadTextdomain extends WP_UnitTestCase { $this->assertSame( get_user_locale(), $this->locale ); } + + /** + * @ticket 58035 + * + * @covers ::load_theme_textdomain + */ + public function test_pre_load_textdomain_filter() { + $override_load_textdomain_callback = new MockAction(); + add_filter( 'override_load_textdomain', array( $override_load_textdomain_callback, 'action' ) ); + + add_filter( 'pre_load_textdomain', '__return_true' ); + load_plugin_textdomain( 'wp-tests-domain' ); + remove_filter( 'pre_load_textdomain', '__return_true' ); + + $this->assertSame( 0, $override_load_textdomain_callback->get_call_count(), 'Expected override_load_textdomain not to be called.' ); + } }