Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

3 Answers 3

up vote 3 down vote accepted

another possibility:

if( $wp_query->current_post < $wp_query->post_count-1 ) echo '<hr />';
share|improve this answer
    
Not that bad :) –  kaiser Sep 26 '12 at 14:25

Actually it's pretty easy:

++$GLOBALS['wpdb']->wpse_post_in_loop < count( $wp_query->posts ) 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.

share|improve this answer
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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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