I have a wordpress widget that has the standard outline like:
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 for your thoughts
I’m plucking this code out of my Total Widget Control plugin, so it might throw an error or two. I dunno, just let me know if it does. This is basically the widget code that I use for everything that I build.
Now, once you’ve pasted this into your functions.php file you can start declaring new widgets in seconds. Here’s the code to declare a new widget.
Declare whatever fields that you want for your widget options with the array above and you’re almost done.
The last thing that you need to do is paste your widgets html into your new file path/to/my/widget_view_file.php
At the top of this widget view file add this following code:
<?php extract($args[1]); ?>
This will break out three variables for you to use:This widget enqueues all possible required scripts for the footer, but it also sets a hook on
wp_print_footer_scripts
that will deregister the scripts before they are printed, unless you change the array when printing the widget.Are you looking to have a script only trigger when the widget is being used?
You could extend the
WP_Widget
class and add your init stuff to the constructor or overload thewidget()
method with your modified code. E.g.