Translation issue with global variables

Translation works with global variables, you just need to wait until the proper hook to call the translation functions. I haven’t looked at the code or documentation, but just by experimenting, the translations are loaded sometime before the after_setup_theme hook, but after the other hooks that fire before that.

That means that if you try to translate something on the plugins_loaded hook, you’re not going to get a translated result back.

As an example, in the following plugin, the first time $dash is “translated” in the main plugin file, it won’t be. It will always print “Dashboard” no matter what. Same thing on the plugins_loaded hook.

The fun part is in the after_setup_theme hook where the global $dash prints in English, but the newly translated text prints (in my case) “Escritorio”.

On the init hook, the global $dash prints the translated text. I added a callback to a closure to make sure that it was displaying the global $dash variable, and it was.

/**
 * Plugin Name: StackExchange Sample
 */

namespace StackExchange\WordPress;

$dash = __( 'Dashboard ' );
printf( '<p>Main plugin file: %1$s</p>', $dash );  // Dashboard

class plugin {
  public function plugins_loaded() {
    \add_action( 'after_setup_theme', [ $this, 'after_setup_theme' ] );
    \add_action( 'init', [ $this, 'init' ] );

    echo '<h2>plugins_loaded</h2>';
    global $dash;
    printf( '<p>Global: %1$s</p>', $dash );  // Dashboard
    $dash = __( 'Dashboard' );
    printf( '<p>Local: %1$s</p>', $dash );  // Dashboard
  }
  public function after_setup_theme() {
    echo '<h2>after_setup_theme</h2>';
    global $dash;
    printf( '<p>Global: %1$s</p>', $dash );  // Dashboard
    $dash = __( 'Dashboard' );
    printf( '<p>Local: %1$s</p>', $dash );  // Escritorio
  }
  public function init() {
    echo '<h2>init</h2>';
    global $dash;
    printf( '<p>Global: %1$s</p>', $dash );  // Escritorio
    $dash = __( 'Dashboard' );
    printf( '<p>Local: %1$s</p>', $dash );  // Escritorio
  }
}
\add_action( 'plugins_loaded', [ new plugin(), 'plugins_loaded' ] );
\add_action( 'init', function() {
  global $dash;
  printf( '<p>Global: %1$s</p>', $dash );  // Escritorio
}, 20 );

In summation: global variables with translated text do work, make sure you wait until after the after_setup_theme hook to translate your text, and don’t use global variables because it’ll just cause problems.