简体   繁体   中英

How to add js-file to wordpress widget?

I try to add test.js file to my widget in front-end part. But it's nothing happens. The file contain alert. What's wrong with my code?

class PPNDR_new_widget extends WP_Widget{
    function __construct(){
        $args = array(
        'name' => 'new widget',
        'description' => 'this is my first widget',
        'classname' => 'ppndr-new-widget'
        );
        parent::__construct('my_first', '', $args);
    }

    //front-end display of widget
    public function widget($args, $instance) {
        add_action('wp_enqueue_scripts', 'CounDounJS_enqueue_js');

        function CounDounJS_enqueue_js() {
            wp_enqueue_script('resize', plugins_url('/assets/js/test.js', __FILE__));
        }
        return;
    }
}

add_action( 'widgets_init', function() {
    register_widget('PPNDR_new_widget');
} );

I had a similar problem and google led me here -- What ended up working for me was eliminating the add_action('wp_enqueue_scripts.. and simply enqueuing my scripts and styles in the widget function.

for example:

    //front-end display of widget
    public function widget($args, $instance) {

        wp_enqueue_script('resize', plugins_url('/assets/js/test.js', __FILE__));

    }

There is the problem of not being able to dequeue the script, but I suspect the need for this would be slim.

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM