So I have a WPQuery loop set up that works great and uses and infinite scroll to keep loading posts in batches of 10 posts. What I would like to do is insert a <div> after every 5th post in the list. I added a counter code to it, but it doesn't seem to give me the desired output, as it only gives me <div> onthe first 5th and 10th posts, but none after that. Here is the code:

 $featuredPosts = get_field('featured_posts');
$excludePosts = [];
foreach($featuredPosts as $key => $postItem) {
  $excludePosts[] = $postItem->ID;

$numPosts = 10;
$args = array(
 'post_type'  => 'post',
 'post_status' => 'publish',
 'posts_per_page' => $numPosts,
 'post__not_in' => $excludePosts

$the_query = new WP_Query( $args );
 if ( $the_query->have_posts() ) {
  $counter = 0;
  while ( $the_query->have_posts() ) {
    <article id="post-<?php echo get_the_ID(); ?>" <?php post_class('frontpage-articles'); ?> >
        <div class="entry-container">
            <div class="post-meta"><span class="entry-date"><?php echo get_the_date("M d, Y", get_the_ID()); ?></span>
                <span class="entry-author">by
                   <a href="<?php echo esc_url(get_author_posts_url(get_the_author_meta('ID'))) ?>"><?php the_author(); ?></a>
            <header class="entry-header">
                <h3 class="entry-title">
                    <?php echo sanitize_title(the_title( '<a href="' . esc_url(get_permalink($post->ID) ) . '">', '</a>' )); ?></h3>
            </header><!-- .entry-header -->

            <div class="entry-summary">
                <?php /*echo substr(strip_tags(get_the_excerpt()), 0,999); */?>
                <?php echo substr(strip_tags(get_the_excerpt()), 0, 120); ?>
            </div><!-- .entry-summary -->
        <!-- #thumbnail-->
        $cloudinaryImage = get_post_meta($post->ID, 'cloudinary_image_id');
        if ( has_post_thumbnail() ) {
            $thumbnailUrl = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ) );

        $thumbnail = '';
        if(!empty($cloudinaryImage[0])) {
            $thumbnail = "https://res.cloudinary.com/upload/".$cloudinaryImage[0];
        } else if(!empty($thumbnailUrl)) {
            $thumbnail = $thumbnailUrl[0];
        } ?>
        <a href="<?php echo esc_url(get_permalink($post->ID))?> ">
            <div class="entry-thumb" style="background-image: url('<?= $thumbnail; ?>'); background-repeat: no-repeat; background-size: cover;" alt="">
        <!-- .thumbnail-image -->
            if ($counter % 5 == 0){
              echo '<div>Ads Test Div to Be inserted after every 5th post</div>';


$counter = 0;
/* Restore original Post Data */
    echo do_shortcode('[ajax_load_more preloaded="false"  offset="13"  exclude"="'.implode(",", $excludePosts).'" images_loaded="false" button_label="Load more" transition_container="false" progress_bar="false" posts_per_page="10" pause="true" pause_override="true" css_classes="infinite-scroll"]');

I don't know why the count isn't working as it should I believe it's in the correct place. Any help would definitely be appreciated.

  • I'm not familiar with the ajax_load_more shortcode. Is it using this loop to render the output? Mar 5, 2019 at 18:54
  • Hi @MikeNGarrett it's a wordPress Plugin used to load posts as infinite scrolling
    – MikeL5799
    Mar 5, 2019 at 21:06

1 Answer 1


It seems that you are using Ajax Load More as a lazy loading method. Your div is displaying only with the elements loaded with the "classic" WP query because the load more shortcode has nothing to do with the code you wrote: is other code, excuted when already your code was parsed, run, an done.

Skimming through its documentation I couldn't find any way to insert yourself in the plugin's own loop without tinkering directly with it's source file, that is a bad idea.

My suggestion would be to, if you absolutely want to use that plugin to do lazy loading, leverage its complete callback function and insert, after the loading is done, your div dynamically counting every 5th post. You will need to setup ajax on frontend first.

Then you bind your special div to an ajax action:

function my_ajax_action(){
   echo "<div> Hello! </div>";
add_action( 'wp_ajax_nopriv_my_ajax_action', 'my_ajax_action' );

and call it from the frontend with some javascript, to place in the footer of the page you need this functionality.

$(function() {

jQuery.fn.insertAt = function(index, element) { //custom function, see below code
  var lastIndex = this.children().size();
  if (index < 0) {
    index = Math.max(0, lastIndex + 1 + index);
  if (index < lastIndex) {
  return this;

  $.fn.almComplete = function(alm){ //this is the ajax load more's callback, view link in answer

    jQuery.ajax(//let's call our custom ajax action
        type: "post",
        dataType: "json",
        url: my_ajax_object.ajax_url, //see link in answer about ajax setup
        data: { action:"my_ajax_action" }, //the custom action
        success: function(my_div){ //what to do when the div is returned from ajax
            jQuery('.loaded_posts').insertAt(4, my_div);
            jQuery('.loaded_posts').insertAt(9, my_div);
            //fixed values because you know how many posts you call

I used the insertAt function from this answer. Other resources were the Wordpress page on AJAX

  • Thanks so much. I was wondering why it didn't work as planned.
    – MikeL5799
    Mar 5, 2019 at 21:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.