Title: dynamically add scripts to WP_Widget widget() method
Last modified: August 19, 2016

---

# dynamically add scripts to WP_Widget widget() method

 *  [oste15](https://wordpress.org/support/users/oste15/)
 * (@oste15)
 * [14 years, 11 months ago](https://wordpress.org/support/topic/dynamically-add-scripts-to-wp_widget-widget-method/)
 * I am creating a widget with the standard widget code like below
 *     ```
       class my_widget extends WP_Widget{
   
       function my_widget(){
          //do setup stuff
       }
   
       function form(){
          //do form stuff
       }
   
       function update(){
          //do update stuff
       }
   
       function widget($args, $instance){
          //how can we dynamically add style and script here
   
          //this does not work
          if($instance['val'] == 'test'){
             wp_register_script('test', plugins_url('test.js');
             wp_print_scripts('test');
          }else{
             wp_register_script('diff', plugins_url('diff.js');
             wp_print_scripts('diff');
          }
       }
       }
       ```
   
 * I am wondering if it’s possible to somehow add scripts dynamically to a wordpress
   widget… I am guessing that this would have to take place within the widget() 
   method b/c that is the only place where dynamic variables are passed, but the
   problem is this function appears to be fired after scripts are added.
 * Thanks a lot for your help on this. My widget is more complex than this and it
   currently includes atleast 5 scripts on each load that are not necessary b/c 
   the only solution i see is to add the scripts in the my_widget() function, which
   does not allow me to dynamically add scripts like i have shown above.

The topic ‘dynamically add scripts to WP_Widget widget() method’ is closed to new
replies.

## Tags

 * [widget](https://wordpress.org/support/topic-tag/widget/)

 * 0 replies
 * 1 participant
 * Last reply from: [oste15](https://wordpress.org/support/users/oste15/)
 * Last activity: [14 years, 11 months ago](https://wordpress.org/support/topic/dynamically-add-scripts-to-wp_widget-widget-method/)
 * Status: not resolved

## Topics

### Topics with no replies

### Non-support topics

### Resolved topics

### Unresolved topics

### All topics
