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.

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.

share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

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;
}
share|improve this answer
    
dynamic_sidebar, got it! –  Sisir Apr 21 '13 at 20:20
    
I tested it. :) It works but the first <hr> is placed right after the second widget not the third. After that it skips three then adds a line. –  s_ha_dum Apr 21 '13 at 20:31
    
@s_ha_dum I made an important update. Could you test it again please? :) –  toscho Apr 21 '13 at 20:32
    
The update works but adds an <hr> at the very top then adds a line after every third item. –  s_ha_dum Apr 21 '13 at 20:35
    
That last edit did it. Perfection. –  s_ha_dum Apr 21 '13 at 20:43
show 3 more comments

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.

share|improve this answer
    
An anonymous object? Why? –  toscho Apr 21 '13 at 20:34
    
Just to kick the constructor. I should have done $sidebar_inserter = new SideBar_Inserter; or made a static class but I am not fond of those. –  s_ha_dum Apr 21 '13 at 20:41
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.