Is it possible to dynamically get sidebar parameters from within a widget? That is, I am trying to access the before_widget
/after_widget
/before_title
/after_title
/name
parameters of the containing sidebar.
Suppose we have a sidebar registered like so:
register_sidebar( array(
'name' => "Homepage Sidebar",
'id' => 'homepage-sidebar',
'before_widget' => '<div id="%1$s" class="widget-container %2$s">',
'after_widget' => '</div>',
'before_title' => '<h2 class="widget-title">',
'after_title' => '</h2>',
) );
How would I access those values from inside my widget’s widget()
function? Like, how would I do something like this:
public function widget( $args, $instance ) {
// outputs the content of the widget
if ($someCondition)
echo $sidebar->before_title . 'My widget title' . $sidebar->before_title;
echo 'You are looking at ' . $sidebar->name;
}
Is this possible?
2 Answers
The parameters are given (as an array) as the first argument provided to the widget
method. The second argument, $instance
, holds the options for that particular instance of the widget.
My usual set up is:
function widget($args, $instance){
//Extract the widget-sidebar parameters from array
extract($args, EXTR_SKIP);
echo $before_widget;
echo $before_title;
//Display title as stored in this instance of the widget
echo esc_html($instance['title']);
echo $after_title;
//Widget content
echo $after_widget;
}