Insert Content After Some Posts In WordPress

Insert Content After Some Posts In WordPress
Insert Content After Some Posts In WordPress

This is a very common usage when you want to add content after some posts in WordPress, like Google Ads, divider or something like that. When reading WPQuestions, I found a good solution for this problem created by Michael Fields.

Add this line to your functions.php file:

add_action( 'the_post', 'clear_gallery_row' );

function clear_gallery_row( $post ) {
    if( is_category( 'gallery' ) ) { // USE A CONDITIONAL HERE TO ISOLATE YOUR GALLERY
        static $count = -1;
        $count++;
        $per_row = 3;
        if( $count >= $per_row ) {
            print ( 0 === ( $count % $per_row ) ) ? '<li class="cleaner"&ht;&nbsp;</li>' . "n": ''; // YOUR CUSTOM CONTENT
        }
    }
}

Thank Michael Fields.

Update: scribu has posted another way (maybe better way) to do the same thing. This is the code provided by scribu. Thank you!

function insert_between_posts($post) {
    global $wp_query;

    // Check if we're in the right template
    if (!is_home()) return;

    // Check if we're in the main loop
    if ($wp_query->post != $post) return;

    // Check if we're at the right position
    if (1 != $wp_query->current_post) return;

    // Display the banner
    echo '<div>Some banner</div>';
}
add_action('the_post', 'insert_between_posts');

1 thought on “Insert Content After Some Posts In WordPress

  1. There is an even easier and better way (IMO).

    Place

    right before

    Place

    <img src="/ads/amazon.gif” width=”470″ height=”70″ alt=”” title=”” border=”0″ />

    right before

    Then you can just change ($showads = 1) to any number you want. Change it to 2 and the ad will show after the second post and so on…

Comments are closed.

Newsletter

Subscribe to our newsletter to receive news and tutorials about WordPress and web development.

Want to get away from Pipdig drama? See 30+ Pipdig blog themes alternatives See here →