WP_Enqueue_Script Loads in Footer, Not Sidebar

I’ve have been working on creating a plugin for WordPress that adds a snippet of code to the sidebar when activated.

So far, the script works when the page is loaded, but it is displayed in the footer of the page instead of the sidebar.

Read More

What should I change to make the code display in the sidebar instead of the footer?

 /**
 * Front-end display of widget.
 *
 * @see WP_Widget::widget()
 *
 * @param array $args     Widget arguments.
 * @param array $instance Saved values from database.
 */


    public function widget( $args, $instance ) {



    echo $args['before_widget'];
    if ( ! empty( $instance['title'] ) ) {
        echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ). $args['after_title'];
        }

      wp_enqueue_script( 'external-script'); 

     //echo __( 'Hello, World!', 'text_domain' );
     echo $args['after_widget'];



}

https://github.com/ModMarc/WordPress-Humanity-Box-Widget/blob/master/Widget.php

Related posts

Leave a Reply

1 comment

  1. wp_enqueue_script loads js files either in the header or footer, never in a sidebar or anywhere else.

    When a script is enqueued after the wp_enqueue_scripts action is fired it is always loaded in the footer.

    From wp_enqueue_scripts documentation:

    As of Version 3.3, the function can be called mid-page (before the wp_footer() template tag) or using the wp_head action hook. This will place the script in the footer as if the $in_footer parameter was set to true.

    If you want a script enqueued in the head, you’ll have to attach your enqueue function to the wp_enqueue_scripts action.

    add_action( 'wp_enqueue_scripts', function() {
        wp_enqueue_script( 'external-script');
    });
    

    This cannot be done in your widget method because that action has already fired by the time the widget is rendered.

    If you want your script loaded in your sidebar, you’ll have to manually output the script tag.

    echo '<script src="' . esc_url($your_script_url) . '"></script>';