Display posts by month

As said in a comment, you can do this in one query. The principle here is to only display the date heading if the post date’s month of the previous post does not match that of the previous post

FEW NOTES

Before I start, a few notes:

  • Never use query_posts, except if you really need to break everything on a page. It not just reruns the main query and also breaks it, it messes up pagination and your globals, and also messes with your queried object functions. If you really have to run a custom query, use WP_Query or get_posts

  • showposts was dropped years ago in favor of posts_per_page

  • No need to make use of the global $wp_query. query_posts messes that up anyway

THE PLAN

Post are served up in chronological order with the newest post first, and the oldest post last, so they are already in the correct order. It is just a matter of displaying the date in the appropriate place.

To do this, all you need to do is to get the current month and year from the current post’s post date, and then comparing that with the previous post’s post date month and then either displaying the date if the months don’t match or not display it if they match

As explanation, I will use the main loop with the main query.

To accomplish this, you need to:

  • Get the month from the current post’s post date. To achieve this, use get_the_date( 'F' )

  • Get the previous post in the loop with $wp_query->posts['this will be current post -1 ']->post.

  • Get and compare the months between the two posts

  • Display or do not display the date according to the comparison

THE CODE

This code goes inside your loop, just after your while() statement.

$current_month = get_the_date('F');

if( $wp_query->current_post === 0 ) { 

   the_date( 'F Y' );

}else{ 

    $f = $wp_query->current_post - 1;       
    $old_date =   mysql2date( 'F', $wp_query->posts[$f]->post_date ); 

    if($current_month != $old_date) {

        the_date( 'F Y' );;

    }

}

CUSTOM QUERY

If you need to run a custom query, try this

$q = new WP_Query( array('post_type' => array( 'lecturas-post' ),'posts_per_page' => 15, 'paged'=>$paged, 'order' => 'DESC' ));

if( $q->have_posts() ) {
    while( $q->have_posts() ) {

        $q->the_post();

        $current_month = get_the_date('F');

        if( $q->current_post === 0 ) { 

           the_date( 'F Y' );

        }else{ 

            $f = $q->current_post - 1;       
            $old_date =   mysql2date( 'F', $q->posts[$f]->post_date ); 

            if($current_month != $old_date) {

                the_date( 'F Y' );;

            }

        }

        the_title();

    }

}

Leave a Comment