Wordpress - How to load Widget javascript + css files only if used?
wp_print_scripts
and wp_print_styles
hooks are fired way before your widget function so that is way it's not working.
A solution to that would be to include the scripts in the footer using wp_print_footer_scripts
hook, take a look at Jan's answer to a similar question
Or a much nicer solution take a look at Sorich's answer to another similar question
Best solution is to register your assets first and then enqueue the CSS and JS inside the widget()
function of your WP_Widget (directly enqueue, not by adding new hooks).
I have tested this solution and it does work in current WordPress version (4.5.3) - both the JS and the CSS are added in the page footer.
<?php
// Register your assets during `wp_enqueue_scripts` hook.
function custom_register_scripts() {
wp_register_style('erw-frontend-css', '...frontend.css');
wp_register_script('jq-hoverintent', '...hoverintent.js', ...);
wp_register_script('jq-tools', '...tools.js', ...);
}
// Use wp_enqueue_scripts hook
add_action('wp_enqueue_scripts', 'custom_register_scripts');
class YourWidget extends WP_Widget {
public function __construct() {
}
public function widget( $args, $instance ) {
// Enqueue needed assets inside the `widget` function.
wp_enqueue_style('erw-frontend-css');
wp_enqueue_script('jq-hoverintent');
wp_enqueue_script('jq-tools');
// Output widget contents.
}
public function form( $instance ) {
}
public function update( $new_instance, $old_instance ) {
}
}