Add Adsense code in index.php

Here is a slight variation of my other answer.

First we register two new widget areas, sidebars in WordPress-speak.

add_action( 'widgets_init', 'wpse_84250_register_ad_widgets' );

function wpse_84250_register_ad_widgets()
{
    // used on the first page of main loop only
    register_sidebar(
        array (
            'name'          => 'Ad Widget 1',
            'id'            => 'ad_widget_1',
            'before_widget' => '<div class="frontpage-ads">',
            'after_widget'  => '</div>'
        )
    );
    register_sidebar(
        array (
            'name'          => 'Ad Widget 2',
            'id'            => 'ad_widget_2',
            'before_widget' => '<div class="frontpage-ads">',
            'after_widget'  => '</div>'
        )
    );
}

You get two new sidebars now in wp-admin/widgets.php. Add text widgets with your ad code here.

enter image description here

Then we insert these widgets into the main loop.

  1. On loop_start we start execution and hook into the_post and loop_end if we are on the front page.
    You can remove this condition …

    if ( ! is_front_page() )
        return;
    

    … if you want to show the ads on all archive listings.

  2. On each call we increment the internal counter $count by one. When the counter is equal to 6 we are below the 5th post an call dynamic_sidebar() to show the first widget.

  3. When the end of the loop was reached or we are below the 10th post we show the second widget and remove our callback to save execution time.

Loop code:

add_action( 'loop_start', 'wpse_84250_show_ad_widgets' );

function wpse_84250_show_ad_widgets()
{
    static $count = 0;

    if ( ! is_front_page() )
        return;

    if ( 'loop_start' === current_filter() )
        return add_action( 'the_post', __FUNCTION__ )
            && add_action( 'loop_end', __FUNCTION__ );

    $count += 1;

    if ( 6 === $count )
        dynamic_sidebar( 'ad_widget_1' );

    if ( 11 === $count or 'loop_end' === current_filter() ) {
        dynamic_sidebar( 'ad_widget_2' );
        remove_action( 'the_post', __FUNCTION__ );
    }
}

You can make a plugin from that code, see: Where do I put the code snippets I found here or somewhere else on the web?

Leave a Comment