__NAMESPACE__ with register_activation_hook

The reason that the plugin activation hook wasn’t working in the code provided in the question is that on plugin activation the plugins_loaded hook is never run. Since the register_activation_hook hook was hooked from plugins_loaded it was never run on activation. And since it’s never fired ever again, this way of hooking results in register_activation_hook never firing.

The solution is to register the activation hook from the main plugin file and not attached to any hooks. In fact, this is the only way that you can run the activation hook. After a plugin is activated there are only two other hooks run: that particular plugin activation hook and shutdown. It’s possible to add hooks to shutdown and they will fire on plugin activation, but it fires after the plugin activation hook.

/**
 * Plugin Name: WordPress Namespace OOP Plugin Example
 */
declare( strict_types = 1 );
namespace StackExchange\WordPress;

//* Start bootstraping the plugin
require( __DIR__ . '/includes/plugin.php' );
$WordPressStackExchangePlugin = new plugin();
\add_action( 'plugins_loaded', [ $WordPressStackExchangePlugin, 'plugins_loaded' ] );

//* Register activation hook
\register_activation_hook( __FILE__, [ __NAMESPACE__ . '\\ActivatorClass', 'activate' ] );

The activation hook would then call the static method activate from the StackExchange\WordPress\ActivatorClass class.

Notes:

  1. Strict typing requires PHP > 7.0.
  2. Array shorthand requires PHP > 5.4
  3. Namespacing and __DIR__ require PHP > 5.3

Leave a Comment