Conditional Widgets based on sidebar
-
I am trying to conditional display some images based on which sidebar a widget lives in. I have these images defined as custom fields.
I am wondering if there is a way for an individual registered widget to know which sidebar it is in using built in WordPress functionality (as opposed to having to navigate the DOM via JavaScript, for example).
Any ideas?
-
Look at the plugin “widget context”. It will display or hide widgets based on a variety of criteria.
Thanks for sending me that direction … It doesn’t quite do what I need it to do, as I am not trying to conditional hide the widget, per se. Rather, I’m trying to hide pieces OF the widget based on its context …
I am currently exploring
wp_get_sidebars_widgets()
as it contains all of the active sidebars with their respective widgets by ID, so I should be able to compare IDs and grab the widget area from there.Thanks again
So! Just as an update for anyone who may be interested in doing the same thing as me, this is relatively simply.
Basically, I needed to know the ID of a given widgets parent widget area. To achieve this, inside the widget() function (in the WP_Widget class) I did the following:
$this_widget_id = $args['widget_id']; $all_widgets = wp_get_sidebars_widgets(); $this_widget_area_id; foreach ( $all_widgets as $widget_area => $widget_ids ) { foreach ( $widget_ids as $widget_order => $widget_id ) { if ( $widget_id == $this_widget_id ) $this_widget_area_id = $widget_area; } }
This allows me to conditionally target pieces of a widget based on the widgets location.
EDIT While this technically solves the problem, it uses the private WP function wp_get_sidebars_widgets() to do so. I’ll find a solution that doesn’t use a private function instead.
- This reply was modified 7 years ago by idealbrandon.
- The topic ‘Conditional Widgets based on sidebar’ is closed to new replies.