So I have this loop which queries posts only from a specific category and displays them with the same style. What I want is to display a different styled post + 1 adsense ad every 5 posts while the others posts keep the same style. Ex: 1 big picture post + 1 ad + 3 small posts. I'm using infinite scroll plugin so it'd be cool to have it this way. I'm still way too newbie at .php and WP so I haven't tried much except for some custom html and css inside to loop, which obviously did not work.
<?php query_posts("cat=8&paged=$paged&posts_per_page=7"); ?>
<?php while ( have_posts() ): the_post(); ?>
<article id="entry-<?php the_ID(); ?>" <?php post_class('entry group'); ?>>
<div id="postcontent"></div>
</article>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
Here's one idea:
Add your custom function or introduce your own hook inside the loop:
<?php while ( have_posts() ): the_post(); ?>
<article id="entry-<?php the_ID(); ?>" <?php post_class('entry group'); ?>>
<div id="postcontent"></div>
</article>
<?php do_action( 'inject_ads', $wp_query->current_post ); ?>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
where you can inject your ads like this:
add_action( 'inject_ads', function( $i ){
if( 4 === $i % 5 )
{
echo '... your ad code ...';
}
});
Here's a table showing how this might work:
i i%5
0 0
1 1
2 2
3 3
4 4 <-- inject ad
5 0
6 1
7 2
In the case of an infinite scroller, you could try to replace
<?php do_action( 'inject_ads', $wp_query->current_post ); ?>
with
<?php do_action( 'inject_ads', $k ); ?>
where
$k = ( $paged > 1 ) ? $wp_query->post_count * ( $paged - 1 ) + $wp_query->current_post : $wp_query->current_post;
to preserve the injection period.
Hope this helps.
Ps: You're using query_posts
, but it's more common to use the pre_get_posts
hook to modify the main query.