I created my widget and try to connect the js file by calling a function

wp_enqueue_script( 'myscript', plugins_url().'/Car/qqw.js','',''); 

but nothing happens. What could be the problem? here is my widget code:

 <?php class btru_widget extends WP_Widget { function __construct() { parent::__construct( 'btru_widget', __('Widget', 'btru_widget_domain'), array( 'description' => __( 'Виджет для вывода Model', 'btru_widget_domain' ), ) ); } public function widget( $args, $instance ) { $title = apply_filters( 'widget_title', $instance['title'] ); echo $args['before_widget']; if ( ! empty($title )) echo $args['before_title'] . $title . $args['after_title']; $args = array( 'taxonomy' => 'Models', 'get' => 'all', 'hide_empty'=>0 ); wp_enqueue_script( 'myscript', plugins_url().'/Car/qqw.js','',''); $terms = get_terms( $args ); echo "<div id='accordion'> <h3>Models</h3> <div>"; foreach( $terms as $term=>$WP_Term){ echo "<p>".$WP_Term->name."</p>"; } echo "</div></div>"; get_footer(); echo $args['after_widget']; } public function form( $instance ) { if ( isset( $instance[ 'title' ] ) ) { $title = $instance[ 'title' ]; } else { $title = __( 'Models', 'btru_widget_domain' ); } ?> <p> <label for="<?php echo $this->get_field_id( 'title' ); ?> "><?php _e( 'Title:' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>" /> </p> <?php } public function update( $new_instance, $old_instance ) { $instance = array(); $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : ''; return $instance; } } function btru_load_widget() { register_widget( 'btru_widget' ); } add_action( 'widgets_init', 'btru_load_widget' ); ?> 

    1 answer 1

    Late!

    wp_enqueue_script () inserts script data into the internal structure of WordPress and does nothing more. During the construction of the header and footer, WordPress extracts information about the scripts and writes them in the header or (if explicitly stated) in the footer.

    Your widget function starts much later than the header generation, so the script does not get into the page code.

    To run the script in the footer, add the fifth parameter true to the wp_enqueue_script call. He is responsible for running in the footer.

    Or connect the script, as expected. Remove the call from the widget and add to the end:

     add_action( 'wp_enqueue_script', 'my_script'); function my_script() { wp_enqueue_script( 'myscript', plugins_url() . '/Car/qqw.js'); } 

    Even more correct is to remove the call from the widget, add a line to __construct ()

     add_action( 'wp_enqueue_script', array( $this, 'my_script' ) ); 

    and inside the class is a function

     public function my_script() { wp_enqueue_script( 'myscript', plugins_url() . '/Car/qqw.js'); }