Another WordPress Development Blog

Use widgets to display ads between posts


In case you want to show ads between the posts displayed on the main page you may want to look into the “widget solution”. Here is a how you can do that.

First of all you need to register a widget. This widget will not be used on sidebar or footer but inside the index page. Copy this code inside functions.php


register_sidebar( array(
'name' => 'advertising',
'id' => 'advertising',
'before_widget' => '<div id="advertising_div">',
'after_widget' => '</div>',
'before_title' => '<h3 class="advertising_div_h">',
'after_title' => '</h3>'
) );

After that, open the index.php and find the loop. Look for endwhile; instruction – It’s marking the end of the loop. Before this line post the code:


$count_posts++;
if ($count_posts==2)
{
dynamic_sidebar('advertising');
$count_posts=0;
}

This code will display the widget advertising every 2 posts. To change this just edit the $count_posts==2 and use the number you want.

Also you need to put this line $count_posts=0; before the loop(just to keep things simple – write it as first line) .

Random Posts

Leave a Reply