0

I know this question has been asked in the past but the accepted answer is incorrect. is_active_widget returns true if the widget is registered on the site. I.e., it was dragged to the right in Appearance > Widgets in the admin or added via the Customizer.

What I'm looking to do is load a script only if the widget is actually present in the sidebar on specific page. Case in point: Template A has a sidebar with a recent posts widget and Template B has a different sidebar with a recent comments widget. I want the script to load on the front end only if the recent comments widget is on the page.

is_active_widget('','','widget_recent_comments') returns true on every page load regardless if the widget is actually loaded, since that widget is registered in the backend.

I know you can call wp_enqueue_script from the widget() method, but that loads in the footer. I need it to load in the header.

  • Why no only load the script on the template that shows the widget rather than if the widget is showing... developer.wordpress.org/reference/functions/is_page_template – Dammeul Apr 7 '16 at 14:39
  • Because I'm building a public widget, I won't know what the templates/sidebars are. The only thing I know is if the widget is active on the site. – darrinb Apr 7 '16 at 14:54
  • I'm not sure you can know if a sidebar is loaded by a theme's html output using WordPress native functions. You could parse wp_get_sidebars_widgets() to check in which sidebars the widget you are targeting is loaded, capture the full html using output buffering and then match the sidebar id in the full html output, but it feels a bit hacky. – Luis Sanz Apr 7 '16 at 16:47
  • need to be in the header or just before the widget? maybe you could load the script at the start of the widget itself? (first instance on page only) – majick Apr 8 '16 at 22:55
0

I think what you are asking to do is not possible. At least not cleanly. Why?

Because the actual rendering of sidebars and widgets happens in the template files. get_sidebar() gets called from a template file which then calls the WP_Widget::widget() method for whichever widgets are assigned to the sidebar in question. But this happens after the wp_head event is called (usually from the header.php template) and scripts queued for the head are printed. So you can't know whether your widget will be actually be loaded by a given theme's templates for the page body on any given page until after the <head> has already been sent.

The most you can know is that if a theme template calls a sidebar in which the widget is active, it will be printed to the page output -- which is what is_active_widget() tells you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.