How to add element after every post in the loop, but not the last one

I have a pretty common loop:global $wp_query, $wpdb;if ( have_posts() ){while ( have_posts() ){the_post();get_template

I have a pretty common loop:

global $wp_query, $wpdb;
if ( have_posts() )
{
    while ( have_posts() )
    {
        the_post();

        get_template_part(
             'template_parts/content'
            ,get_post_format()
        );
    }
}
else
{
    get_template_part( 'no_results' );
}

Now I need to add (for example) a <hr /> after each single post, but not the last one.

How would I determine if I currently got the second to last post in the current loop?

Note: This should work for paged loops as well.

I have a pretty common loop:

global $wp_query, $wpdb;
if ( have_posts() )
{
    while ( have_posts() )
    {
        the_post();

        get_template_part(
             'template_parts/content'
            ,get_post_format()
        );
    }
}
else
{
    get_template_part( 'no_results' );
}

Now I need to add (for example) a <hr /> after each single post, but not the last one.

How would I determine if I currently got the second to last post in the current loop?

Note: This should work for paged loops as well.

Share Improve this question asked Sep 26, 2012 at 13:37 kaiserkaiser 50.9k27 gold badges151 silver badges245 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 3

another possibility:

if( $wp_query->current_post < $wp_query->post_count-1 ) echo '<hr />';
global $wp_query, $wpdb;
if( have_posts() ) {
    $total_posts = $wp_query->found_posts;
    $i = 0;
    while( have_posts() ) {
        the_post();
        $i++;
        get_template_part(
                'template_parts/content'
                , get_post_format()
        );
        if( $i != $total_posts ) {
            echo '<hr />';
        }
    }
} else {
    get_template_part( 'no_results' );
}

It would be okay to remove $wpdb too because it is not being used anywhere in this example.

Actually it's pretty easy:

( $wpse_counter = count( $wp_query->posts ) ) && ++$GLOBALS['wpdb']->wpse_post_in_loop < $wpse_counter AND print "<hr />";

Calling the global with $GLOBALS['wpdb'] will allow modifying the global itself. Therefore I use a custom, prefixed property named wpse_post_in_loop to not in interfere with core settings, properties, etc.

The above line is just for elegance. If you want to keep this fast, it's better to do the count() part in front of the loop.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745085158a4610362.html

相关推荐

  • How to add element after every post in the loop, but not the last one

    I have a pretty common loop:global $wp_query, $wpdb;if ( have_posts() ){while ( have_posts() ){the_post();get_template

    18小时前
    20

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信