How to load Widget javascript + css files only if used?

I’d like to keep the javascript and css styles used by my widget inside their own files (and not add them to the theme).

But i can’t seem to get wordpress to add them when the widget is actually used on a sidebar.

Read More

I’ve tried this:

inside the Class declaration, i’ve added 2 functions

class EssentielleRubriquesPosts extends WP_Widget {

function addFrontendCss(){
    wp_enqueue_style('erw-frontend-css', ESSENTIELLE_RUBRIQUE_WIDGET_PLUGIN_PATH . 'css/EssentielleRubriqueWidget-frontend.css');
}
function addFrontendJavascript(){
    wp_register_script('jq-hoverintent', PLUGIN_PATH . 'js/jquery.hoverintent.js', array('jquery'), '1.0',true);
    wp_enqueue_script('jq-hoverintent');
    wp_enqueue_script('jq-tools', PLUGIN_PATH . 'js/jquery.tools.js', array('jquery'),'1.0',true);
    wp_enqueue_script('erw-frontend-js', PLUGIN_PATH . 'js/widget-frontend.js', array('jquery', 'jq-hoverintent', 'jq-tools'),'1.0',true);

}

and inside the widget() function:

function widget($args, $instance) {
        add_action( 'wp_print_scripts', 'addFrontendJavascript' );
        add_action( 'wp_print_styles', 'addFrontendCss' );
}

But that doesn’t do anything…

Related posts

Leave a Reply

2 comments

  1. 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 ) {
        }
    }