Unable to to self-deactivate plugin using deactivate_plugins()

I have these plugin files:

  • my-plugin/my-plugin.php
  • my-plugin/my-plugin-class.php

In my-plugin.php I have the following line:

register_activation_hook( __FILE__, array( $my_plugin_object, 'on_activate_my_plugin' ) );

In my-plugin-class.php I have the following methods:

public function on_activate_my_plugin() {
    if ( // Some validation failed ) {
        wp_mail( '[email protected]' , 'test', 'test' );

        deactivate_plugins( 'my-plugin/my-plugin.php' );
        add_action( 'admin_notices', array( $this, 'my_plugin_activation_failed' ) );
    }
}

public function my_plugin_activation_failed() {
    ?div class="notice notice-error"pThe strongMy Plugin/strong could not be activated because of something./ppDo the thing and activate the plugin./p/div?php
}

I get the e-mail but nothing else happens.
The plugin does not self-deactivate.
I am also not getting the admin notice.

What am I doing wrong?

Thank you!

Topic deactivated-plugin plugins Wordpress

Category Web


Activation hook is fired while the plugin is being activated, at best it is a dangerous assumption to make that at that point it is already active, and if it is not active, obviously you can not deactivate it.

If you are looking for a way to fail the activation, the best way is probably to die()

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.