Skip to content

Instantly share code, notes, and snippets.

@pablo-sg-pacheco
Last active December 19, 2022 21:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pablo-sg-pacheco/7b92acd6bed3c22ded38c9c9811d1c3b to your computer and use it in GitHub Desktop.
Save pablo-sg-pacheco/7b92acd6bed3c22ded38c9c9811d1c3b to your computer and use it in GitHub Desktop.
Custom deactivation/activation hooks from a WordPress plugin that can be called from some other hooks
<?php
// Custom deactivation/activation hooks.
$activation_hook = 'plugin_prefix_on_activation';
$deactivation_hook = 'plugin_prefix_on_deactivation';
register_activation_hook( __FILE__, function () use ( $activation_hook ) {
add_option( $activation_hook, 'yes' );
} );
register_deactivation_hook( __FILE__, function () use ( $deactivation_hook ) {
do_action( $deactivation_hook );
} );
add_action( 'admin_init', function () use ( $activation_hook ) {
if ( is_admin() && get_option( $activation_hook ) === 'yes' ) {
delete_option( $activation_hook );
do_action( $activation_hook );
}
} );
@pablo-sg-pacheco
Copy link
Author

pablo-sg-pacheco commented Dec 19, 2022

The custom activation hooks can be called from some other hooks like plugins_loaded or init. Example:

add_action( 'plugins_loaded', function () {
	add_action( 'plugin_prefix_on_activation', function () {
		error_log( 'plugin activated' );
	} );
	add_action( 'plugin_prefix_on_deactivation', function () {
		error_log( 'plugin deactivated' );
	} );
} );

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment