Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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?

share|improve this question
add comment

2 Answers 2

up vote 2 down vote accepted

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;

 }
share|improve this answer
    
As far as I understood the question, the OP wants to have data from the sidebar, not the widget. –  kaiser Jun 25 '12 at 18:34
    
Yes me too - that is what the $args are (also includes widget ID and widget name), whereas $instance are the widget options. See source ($sidebar contains the data from register_sidebar) –  Stephen Harris Jun 25 '12 at 18:50
add comment

Use variable name only, like:

$name
$before_title
$after_title
$before_widget
$after_widget
share|improve this answer
    
Don't know why this was downvoted... it's actually correct. –  supertrue Jun 27 '12 at 21:10
    
Because it got no further explanation. Stumbled upon it, when the system flagged it as "low quality" i guess - made dozens of up-/downvotes yesterday to get flags done. If you edit something and leave me a comment, I'll remove the downvote. –  kaiser Jun 29 '12 at 20:13
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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