Hooks.php
65 lines
| 1 | <?php |
| 2 | |
| 3 | namespace WCML\MO; |
| 4 | |
| 5 | use WPML\LIB\WP\WordPress; |
| 6 | use function WPML\Container\make; |
| 7 | |
| 8 | class Hooks implements \IWPML_Backend_Action, \IWPML_Frontend_Action { |
| 9 | |
| 10 | const WC_DOMAIN = 'woocommerce'; |
| 11 | |
| 12 | private $isLoading = false; |
| 13 | |
| 14 | public function add_hooks() { |
| 15 | add_action( 'wpml_language_has_switched', [ $this, 'forceRemoveUnloadedDomain' ], 0 ); |
| 16 | |
| 17 | if ( WordPress::versionCompare( '>', '6.4.999' ) ) { |
| 18 | add_filter( 'override_unload_textdomain', [ $this, 'forceUnloadWCTextdomainWithReloadableArg' ], 10, 3 ); |
| 19 | add_filter( 'pre_load_textdomain', [ $this, 'preLoadTextDomainFilter' ], 10, 4 ); |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | public function forceRemoveUnloadedDomain() { |
| 24 | if ( isset( $GLOBALS['l10n_unloaded'][ self::WC_DOMAIN ] ) ) { |
| 25 | unset( $GLOBALS['l10n_unloaded'][ self::WC_DOMAIN ] ); |
| 26 | } |
| 27 | } |
| 28 | |
| 29 | public function forceUnloadWCTextdomainWithReloadableArg( $override, $domain, $reloadable ) { |
| 30 | if ( self::WC_DOMAIN === $domain && ! $reloadable ) { |
| 31 | unload_textdomain( self::WC_DOMAIN, true ); |
| 32 | \WP_Translation_Controller::get_instance()->unload_textdomain( self::WC_DOMAIN ); |
| 33 | return true; |
| 34 | } |
| 35 | |
| 36 | return $override; |
| 37 | } |
| 38 | |
| 39 | public function preLoadTextDomainFilter( $loaded, $domain, $mofile, $locale ) { |
| 40 | if ( self::WC_DOMAIN === $domain && ! $this->isLoading ) { |
| 41 | $this->forceRemoveUnloadedDomain(); |
| 42 | |
| 43 | if ( ! $locale ) { |
| 44 | $this->maybeFixDiscrepancyBetweenFileLocaleAndControllerLocale( $loaded, $domain, $mofile ); |
| 45 | } |
| 46 | |
| 47 | } |
| 48 | |
| 49 | return $loaded; |
| 50 | } |
| 51 | |
| 52 | private function maybeFixDiscrepancyBetweenFileLocaleAndControllerLocale( $loaded, $domain, $mofile ) { |
| 53 | $fileLocale = make( \WPML_ST_Translations_File_Locale::class ); |
| 54 | $localeFromFile = $fileLocale ? $fileLocale->get( $mofile, $domain ) : null; |
| 55 | |
| 56 | if ( $localeFromFile && $localeFromFile !== \WP_Translation_Controller::get_instance()->get_locale() ) { |
| 57 | $this->isLoading = true; |
| 58 | $loaded = load_textdomain( $domain, $mofile, $localeFromFile ); |
| 59 | $this->isLoading = false; |
| 60 | } |
| 61 | |
| 62 | return $loaded; |
| 63 | } |
| 64 | } |
| 65 |