最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

php - Is there an option to execute javascript file only on plugin activation

programmeradmin2浏览0评论

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.

Share Improve this question asked Jul 26, 2019 at 20:54 upss1988upss1988 178 bronze badges 3
  • 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
Add a comment  | 

1 Answer 1

Reset to default 0

Here 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' );
    }
}
发布评论

评论列表(0)

  1. 暂无评论