Dirty Bird Design
Dirty Bird Design

Reputation: 5553

Insert div BEFORE last post on page

I want to insert a div before the last returned post on a page from the loop. I am displaying 10 posts per page, and can easily do

<?php if ($counter === 9)....

which if the page shows 10 posts works. However, if there are say 23 returned posts, the last page will only show 3, if there are fewer than 10 that wouldn't show up.

I can get it to insert after the last post like this:

<?php if (($the_query->current_post +1) == ($the_query->post_count))....

But can't get it to insert BEFORE the last post

Here is the complete loop:

<?php 
    $paged = ( get_query_var('page') ) ? get_query_var('page') : 1;

    $query_args = array(
        'posts_per_page' => 10,
        'post_status' => 'publish',
        'post_type' => 'post',
        'paged' => $paged,
        'page' => $paged
    );

    $the_query = new WP_Query( $query_args ); $counter = 1; ?>

    <?php if ( $the_query->have_posts() ) : ?>
    <!-- the loop -->
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
    <div class="entry">
        <h2><?php the_title(); ?></h2>
        <p>Written by: <?php the_author_posts_link(); ?> | <?php the_date(); ?></p>
        <!-- show thumbnail on first .entry only -->
        <?php 
            if ($counter === 1 ) {
                the_post_thumbnail();
        }?>
        <?php the_excerpt(); ?>
    </div>
    <!-- insert ad after 3rd  -->
    <?php if ($counter === 2) {
        echo '<img src="/wp-content/uploads/2016/01/780x90_1.png">';
    }?>
    <!-- insert before last -->
    <?php if (($the_query->current_post +1) == ($the_query->post_count)) {
                          echo '<img src="/wp-content/uploads/2016/01/780x90_1.png">';
                        } ?>

    <?php $counter++ ; endwhile; ?>

....

Upvotes: 0

Views: 76

Answers (3)

Dirty Bird Design
Dirty Bird Design

Reputation: 5553

Thanks to @Loai, he got me on the right track.

<?php if (($the_query->current_post +1) == ($the_query->post_count -1))

Upvotes: 0

Loai Abdelhalim
Loai Abdelhalim

Reputation: 1967

The $found_posts variable will return the total number of posts you have.

Do a comparison against $the_query->current_post with $found_posts subtracted by 1.

Example:

if (($the_query->current_post) == ($the_query->found_posts - 1)){
// Insert div.
}

Upvotes: 3

DigiDamsel
DigiDamsel

Reputation: 106

Would this work?

<php? if (($the_query->current_post +1) == (($the_query->postcount)-1))...

Or set up a variable first to check against that is equal to the second value.

Upvotes: 0

Related Questions