php – How can I translate something in my class constructor of my plugin in WordPress?


I’ve a problem. I’m currently developing a plugin including a check for dependencies. So I’ve included a check in my plugin root class before calling all other init methods:

public function __construct() {
    $this->init_core_hooks();

    if ( ! Pmx_Dependencies::get_instance()->is_loadable() ) {
        return;
    }

    $this->init_classes();
}

private function init_core_hooks(): void {
    add_action( 'plugins_loaded', ( $this, 'plugins_loaded_action' ) ); // Here I'm loading my translation files
}

The problem is that in case a dependency is missing I’m adding a admin notice to WordPress but it’s not getting translated:

public function __construct() {
    if ( ! function_exists( 'get_plugins' ) || ! function_exists( 'is_plugin_active' ) ) {
        require_once ABSPATH . 'wp-admin/includes/plugin.php';
    }
    if ( ! function_exists( 'wp_create_nonce' ) ) {
        require_once ABSPATH . WPINC . '/pluggable.php';
    }
    if ( $this->is_yoast_installed() ) {
        $admin_notice = (
            'type'    => 'error',
            'content' => __( 'An error occured', 'pmx' )
        );
        $this->add_admin_notice( $admin_notice );
    }
}

I found out that translation is not ready yet cause the hook where I init my translation file get’s called after I’m adding the notice that something is missing…

So how should I handle this by also following the instructions for loading text files in WordPress??

How to Internationalize Your Plugin

Thanks for any help!