I’m new to wordpress development and created a widget that works fine, however I’m not sure how to dependently load the necessary JS for the widget.
Current code is:
wp_enqueue_script('my_script', '/path/to/necessary.js');
class widget extends WP_Widget {
function widget(){
....
}
}
I’d like to only load that script if/when the widget is actually included on the page. Since it’s not on every page, I’m wastefully loading JS on some pages. If I put the wp_enqueue_script
in the widget
function, it doesn’t work since it’s in the template loop and the headers have already been written out. I know I can just drop a <script>
tag into the widget
function, but that seems to go against WP standards, so I’m looking for the “correct” way to do this.
take a look at
is_active_widget( $callback, $widget_id, $id_base, $skip_inactive );
Only load a script when the widget is active:
http://codex.wordpress.org/Function_Reference/is_active_widget
Most WordPress widgets are used on all “user” – rather than admin – pages. Basically you need to determine what pages load the widget, test for it, and if it passes, add the script to the header. If it is just the front page, then you can test for that with php in the header and enqueue the script… If it is a page with a specific category, check for that and enqueue the script… you get the picture. The wordpress codex is your friend