Skip to content

Instantly share code, notes, and snippets.

@imagebox
Created February 11, 2021 20:07
Show Gist options
  • Save imagebox/72197ca6ceb564429e8f6580bd5a08ce to your computer and use it in GitHub Desktop.
Save imagebox/72197ca6ceb564429e8f6580bd5a08ce to your computer and use it in GitHub Desktop.
[WordPress | Query Post Type, Group By Year] #WordPress #CPT
// see example https://www.carnegiehero.org/heroes/latest-award-announcements/press-releases/
<?php
$oldest = get_posts( 'post_type=post&post_status=publish&posts_per_page=1&order=ASC' );
$oldest_date = $oldest[0]->post_date;
$first_date = date('Y', strtotime($oldest_date));
$todays_date = date('Y');
$year_range = range($todays_date, $first_date);
foreach ($year_range as $year) {
echo '<h2>' . $year . '</h2>';
$args = array(
'posts_per_page' => -1,
'post_type' => 'awardee_pr',
'post_status' => 'publish',
'year' => $year,
);
$yearly_posts = new WP_Query($args);
if($yearly_posts->have_posts()) {
echo '<ul>';
while($yearly_posts->have_posts()) {
$yearly_posts->the_post();
echo '<li><h3><span>' . get_the_date( 'F j, Y' ) . ': </span>';
echo '<a href="';
echo the_permalink();
echo '">';
echo get_the_title();
echo '</a></h3></li>';
}
echo '</ul>';
}
}
wp_reset_postdata();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment