Inserting a banner between posts
It’s pretty easy to inject content between posts if you have direct access to The Loop in the theme:
$counter = 0; while ( have_posts() ) : the_post(); if ( 1 == $counter ) echo '<div>Some banner</div>'; $counter++; // the_title() etc. endwhile;
If you want to do this without modifying the theme, the solution is not so obvious, but it exists:
function insert_between_posts( $post ) { global $wp_query; // 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' );
Note that with this second approach, the banner will be displayed throughout the site. Fortunately, this can be easily controlled using conditional tags:
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' );
I hope this gives you some ideas for your next great plugin or child theme. Happy hacking!
