2

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.

2 Answers 2

3

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; } 
8
  • dynamic_sidebar, got it! Commented Apr 21, 2013 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. Commented Apr 21, 2013 at 20:31
  • @s_ha_dum I made an important update. Could you test it again please? :) Commented Apr 21, 2013 at 20:32
  • The update works but adds an <hr> at the very top then adds a line after every third item. Commented Apr 21, 2013 at 20:35
  • That last edit did it. Perfection. Commented Apr 21, 2013 at 20:43
1

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.

2
  • An anonymous object? Why? Commented Apr 21, 2013 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. Commented Apr 21, 2013 at 20:41

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.