在页面上的最后一篇文章之前插入div

时间:2016-01-18 17:18:56

标签: php wordpress loops

我想在循环页面上的最后一个返回帖子之前插入一个div。我每页显示10个帖子,可以轻松完成

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

如果页面显示10个帖子有效。但是,如果有23个返回的帖子,则最后一页只显示3,如果少于10个则不会显示。

我可以在最后一篇文章之后插入这样的内容:

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

但是不能在最后一篇文章之前插入

这是完整的循环:

<?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; ?>

...

3 个答案:

答案 0 :(得分:3)

$ found_posts变量将返回您拥有的帖子总数。

与$ the_query-&gt; current_post进行比较,将$ found_posts减去1。

示例:

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

答案 1 :(得分:0)

这会有用吗?

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

或者先设置一个变量来检查它是否等于第二个值。

答案 2 :(得分:0)

感谢@Loai,他让我走上正轨。

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