admin管理员组文章数量:1418696
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' );
}
}
本文标签: phpIs there an option to execute javascript file only on plugin activation
版权声明:本文标题:php - Is there an option to execute javascript file only on plugin activation 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745292065a2651856.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论