avatar Deluxe Blog Tips About Projects

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;
        $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');

🔥 HOT: Interested in boosting your WordPress SEO? My Slim SEO plugin is a super lighweight and automated plugin that handles most the hard work for you: meta tags, sitemap, redirection, schema & link building.

👉 Have a look and you will love it: wpslimseo.com