Hooking Into Widget Output Loop

When wordpress sidebar outputs any particular registered sidebar it loop through all widgets that assigned through it and outputs it (i guess). Is is possible to hook into the loop and add some content, say I want to add a ad code every three widgets.

What I have tried? Unable to find any leads. Tried to search on wordpress source code but not sure what to search. searching widget or widget loop doesn’t help.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Hook into 'dynamic_sidebar' and count how often it is called.

You get the current active sidebar with key( $GLOBALS['wp_registered_sidebars'] ).

add_action( 'dynamic_sidebar', 'wpse_96681_hr' );

function wpse_96681_hr( $widget )
{
    static $counter = 0;

    // right sidebar in Twenty Ten. Adjust to your needs.
    if ( 'primary-widget-area' !== key( $GLOBALS['wp_registered_sidebars'] ) )
        return;

    if ( 0 !== $counter && 0 === $counter % 3 )
        print '<hr>';

    $counter += 1;
}

Method 2

Almost the same as toscho’s but I made a class.

class SideBar_Inserter {
  static $count = 0;

  function __construct() {
    add_action( 'dynamic_sidebar', array($this,'insert_into_sidebar') );
  }

  function insert_into_sidebar($s) {
    if (static::$count !== 0 && static::$count%3 === 0) {
      echo static::$count;
    }
    static::$count++;
  }
}
$sidebar_inserter = new SideBar_Inserter;

This is tested. It works.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x