简体   繁体   中英

Run JS file only on activation and deactivation of plugin in WordPress

I have created custom Divi module and then convert it to the plugin. Divi page builder saves local storage variables so my module is not displaying in the modules list until I clears local storage. I have added JS file that clears storage and its works fine. but I want that js runs only at activation and deactivation.

Below is Plugin activation code

 function angelleye_setup_For_paypal_divi_install()
    {    
            // trigger our function that registers PayPal for Divi plugin.     
            angelleye_setup_for_paypal_divi();                        
    }
    register_activation_hook( __FILE__, 'angelleye_setup_For_paypal_divi_install' );

This is how I adding my js file in plugin.

function paypal_divi_clear_local_storage () {
    wp_enqueue_script( 'paypal_divi_clear_local_storage', plugins_url('assets/js/clear_local_storage.js',__FILE__ ));        
}
add_action( 'admin_enqueue_scripts', 'paypal_divi_clear_local_storage', 9999 );

Here add_action is not calling from the activation function.

Create new function that add your custom option and call function on activation hook:

New Function

register_activation_hook( __FILE__, 'my_plugin_activation' );
function my_plugin_activation() {
  add_option( 'my_plugin_activation','just-activated' );
}

Set below code on time of init action this will work on activation time:

function mycustom_plugin()
{

    if( is_admin() && get_option( 'my_plugin_activation' ) == 'just-activated' ) 
   {
       delete_option( 'my_plugin_activation' );
       wp_enqueue_script( 'paypal_divi_clear_local_storage', plugins_url('assets/js/clear_local_storage.js',__FILE__ ));
    }
}
add_action( 'init', 'mycustom_plugin' );

I hope this may help you.

Please include these lines in your plugin file..

/*
Plugin Name: Plugin_Name
*/


class Plugin_Name       /* Define the name of the plugin or file */
{
  public function __construct()
  {
    add_action('wp_footer', array($this, 'enqueue_js_files'));
  }

  public function enqueue_js_files()
  {
    wp_register_script('clear_local_storage', plugins_url('clear_local_storage.js', __FILE__), array('jquery'), '', true);
    wp_enqueue_script('clear_local_storage');
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM