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.
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
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:
If you want a script enqueued in the head, you’ll have to attach your enqueue function to the
wp_enqueue_scripts
action.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.