Created
November 22, 2016 02:39
-
-
Save kingkool68/217579946b95b803529febcb19d8af8c to your computer and use it in GitHub Desktop.
Grouping the results of a WordPress loop by month and year
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$args = array(...); | |
$my_posts = new WP_Query( $args ); | |
$the_year = ''; | |
$the_month = ''; | |
if ( $my_posts->have_posts() ) : | |
while ( $my_posts->have_posts() ) : | |
$my_posts->the_post(); | |
// Get the year of the post in YYYY format | |
$post_year = get_the_time( 'Y' ); | |
if ( $post_year != $the_year ) { | |
$the_year = $post_year; | |
$the_month = ''; | |
echo '<h1>' . $the_year . '</h1>'; | |
} | |
// Get the month of the post i.e. January, February etc. | |
$post_month = get_thetime( 'F' ); | |
if ( $post_month != $the_month ) { | |
$the_month = $post_month; | |
echo '<h2>' . $post_month . '</h2>'; | |
} | |
echo '<p><a href="' . get_permalink() . '">' . the_title() . '</a></p>'; | |
endwhile; | |
endif; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment