Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

I want to register a script when my plugin is activated. So I wrote:

register_activation_hook(__FILE__, 'register_script');
function register_script(){
   wp_register_script('addjs','http://example.com/exmple.js');
}

Next, I created a meta box and enqueued the script in the add_meta_boxes hook:

wp_enqueue_script('addjs');

But that doesn't work. Why? My js file is just a simple alert function. However, when I register my script using init hook or other hook, my code works - why?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

Whatever is hooked to activation runs in just a single request when the plugin is activated in a sandbox, and the output is captured to check for errors. Your code won't run on any subsequent request after that single activation, so your script will not be registered. It works on init because that action runs on every request.

share|improve this answer
    
err, I actually quite confuse, actually i just want to register my script once when my plugin activated right?> –  dramasea Sep 9 '13 at 18:07
1  
you have to register it on every request you want it present on. code hooked to an action doesn't persist beyond the single request you hooked it on. –  Milo Sep 9 '13 at 18:18
    
okok, thanks is there any hook that only occur in admin area, so that I does not register the script on my front end too, as the script is only used in admin area –  dramasea Sep 9 '13 at 18:31
1  
use admin_enqueue_scripts hook to add js to admin-only pages. if you're doing it all in one place, you can skip registering the script and just use wp_enqueue_script with the same parameters. registering and enqueueing separately are helpful if your script is conditionally enqueued in different places in your code, but it's not necessary to do both if all the parameters are passed with wp_enqueue_script. –  Milo Sep 9 '13 at 18:37
    
Thanks bro, last question.If I want to deregister script I should deregister everytime or once in the plugin deactivation hook? –  dramasea Sep 9 '13 at 18:42

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.