user1556571
user1556571

Reputation:

Display html.Div after nth post within Wordpress loop

Using custom wordpress loop:

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
//Post Content
<?php endwhile;?>
//Pagination
<?php else : ?>
//No posts message
<?php endif; ?>

I need help restructure the code to display html Div.block after 4th post each page on condition that page has at least 6 posts to display.

Upvotes: 1

Views: 1071

Answers (2)

user1556571
user1556571

Reputation:

I defined $postnum before my loop through each result, so that the original value of $postnum can be incremented each iteration.

<?php 
$postnum = 0; // Set counter to 0 outside the loop
if (have_posts()) : while (have_posts()) : the_post();
?>
  //Post Content
<?php $postnum++; // Increment counter
if ($postnum == 4){ ?>
  //Div.block
<?php } ?>
<?php endwhile;?>
  //Pagination
<?php else : ?>
  //No posts message
<?php endif; ?>

That way, I was able to display single Div.block html after 4th post on each page within loop.

Upvotes: 1

Nomce
Nomce

Reputation: 775

WordPress uses the object WPQuery in The Loop, and in the object you have two variables that you can use to determine the number of posts that you will display on the page. The variables are $wp_query->post_count; and $wp_query->found_posts; if you declare the $wp_query like this $wp_query = new WP_Query( $args );.

Now, I will add a little counter in your loop, and it will become this:

<?php 
$size = $wp_query->post_count;
$counter = 0;
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
//Post Content
    if ($size >= 6 && $counter == 3) {
        //show your div here
    }

    $counter++;
<?php endwhile;?>
    //Pagination
<?php else : ?>
    //No posts message
<?php endif; ?>

Upvotes: 0

Related Questions