I have developed a WP Query that displays posts from a custom post type and taxonomy, and orders them by date using a custom field.
The posts have a single Advanced Custom Fields date picker field that is used to set the month and year for each post. The display format for the date picker is a custom value of F Y
and the return format is Ymd
.
Using this field, I have been able to display the posts by year, with posts from the most current year displayed first. I also need to display them by month using the January through December ordering. Currently they are displayed in reverse order because of the query parameters.
Example of how output currently displays:
2024
- 2024 February Post Name
- 2024 January Post Name
- ...
2023
- 2023 February Post Name
- 2023 January Post Name
- ...
Example of how output should display:
2024
- 2024 January Post Name
- 2024 February Post Name
- ...
2023
- 2023 January Post Name
- 2023 February Post Name
- ...
Update
I have converted the single date/time custom field into two, one for the month and the other for the year.
The query has been updated to use the new custom fields. The ordering either uses month or year in ASC or DESC order, but not a combination of the two.
I have tried with using relation => 'AND'
in the meta query, but it has not resolved the issue. I have also tried re-ordering the month and year clauses in the orderby
section, but it only affects the month or the year, and not the two combined.
Here is the updated query:
$args = array(
'post_type' => 'document',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'document-category',
'field' => 'slug',
'terms' => array( 'minute' ),
),
),
'meta_query' => array(
'relation' => 'AND',
'year_clause' => array(
'key' => 'minutes_posted_year',
'compare' => 'NUMERIC',
),
'month_clause' => array(
'key' => 'minutes_posted_month',
'compare' => 'NUMERIC',
),
),
'orderby' => array(
'year_clause' => 'DESC',
'month_clause' => 'ASC',
),
);
And here is the $posts
loop outputting the query:
<?php if ( $posts ) : ?>
<?php foreach( $posts as $post ) {
$month_date = get_field( 'minutes_posted_month', $post->ID, false );
$year_date = get_field( 'minutes_posted_year', $post->ID, false );
$month_date = new DateTime( $month_date );
$year_date = new DateTime( $year_date );
$year = $year_date->format( 'Y') ;
$month = $month_date->format( 'F' );
$group_posts[$year][$month][] = array( $post, $year_date, $month_date );
} ?>
<?php foreach ($group_posts as $yearKey => $years) : ?>
<h3><?php echo esc_html( $yearKey ); ?></h3>
<?php foreach ($years as $monthKey => $months) : ?>
<nav>
<?php foreach ($months as $postKey => $posts) : ?>
<a href="<?php echo esc_url( get_permalink( $posts[0]->ID ) ); ?>">
<?php echo esc_html( $posts[0]->post_title ); ?>
</a>
<?php endforeach; ?>
</nav>
<?php endforeach; ?>
<?php endforeach; ?>
<?php endif; ?>