I'm creating a custom plugin for WordPress and I'm trying to execute javascript
file only once right after plugin activations.
I'm using register_activation_hook()
and wp_enqueue_script()
to execute file only once when the plugin is activated.
There are no errors in the code since the javascript
code works well if it is called outside the register_activation_hook()
.
This is what I've tried so far:
register_activation_hook( __FILE__, 'full_install' );
function full_install() {
function rest_api() {
wp_enqueue_script('activation_data_api', plugins_url('assets/js/activation_data_api.js', __FILE__));
}
add_action( 'admin_enqueue_scripts', 'rest_api' );
}
In the end, the plugin needs to execute javascript
file only once right after activation.
I'm creating a custom plugin for WordPress and I'm trying to execute javascript
file only once right after plugin activations.
I'm using register_activation_hook()
and wp_enqueue_script()
to execute file only once when the plugin is activated.
There are no errors in the code since the javascript
code works well if it is called outside the register_activation_hook()
.
This is what I've tried so far:
register_activation_hook( __FILE__, 'full_install' );
function full_install() {
function rest_api() {
wp_enqueue_script('activation_data_api', plugins_url('assets/js/activation_data_api.js', __FILE__));
}
add_action( 'admin_enqueue_scripts', 'rest_api' );
}
In the end, the plugin needs to execute javascript
file only once right after activation.
- Yes, there is. – Sally CJ Commented Jul 26, 2019 at 23:53
- @SallyCJ I've tried with that, but probably I've done something wrong because it didn't work. Can you please show me on my example how can I do that? – upss1988 Commented Jul 27, 2019 at 8:08
- Well, you've already got it correct now. :) – Sally CJ Commented Jul 27, 2019 at 13:56
1 Answer
Reset to default 0Here is the solution:
register_activation_hook( __FILE__, 'rest_api_hook' );
/**
* Runs only when the plugin is activated.
*/
function rest_api_hook() {
/* Create data */
set_transient( 'rest_api', true, 5 );
}
/* Add notice */
add_action( 'admin_notices', 'rest_api_hook_exec' );
/**
* Rest API Notice on Activation.
*/
function rest_api_hook_exec() {
/* Check transient, if is available display notice */
if( get_transient( 'rest_api' ) ) {
// Execute script
wp_enqueue_script('activation_data_api', plugins_url('assets/js/activation_data_api.js', __FILE__));
// Delete script after executing
delete_transient( 'rest_api' );
}
}