Home › Forums › General Issues › Dates by Year, just last 4 years
I’m sure there is an easier way to do this, tho my code currently works.
I set up my own events system with ACF.
I want to list the last 4 years of events with a date headers(rolling events, so that as the year changes, the very end of the list drops off):
2012
Event 1
Event 2
Event 4
2013
Event 1
Event 2
2013
Event 1
Event 2
Event 3
Event 4
etc…
The number of events changes per year.
Right now I’m basically setting the dates in variables, then setting the meta_queries in a variable and then running 4 WP_Query 4 separate times.
<?php
$year1 = date('Y',strtotime(date('Y-01-01')));
$year2 = $year1 -1;
$year3 = $year1 -2;
$year4 = $year1 -3;
$year5 = $year1 -4;
$thisyear = array(
array(
'key' => 'event-date',
'compare' => '>',
'value' => $year1,
),
);
$lastyear = array(
array(
'key' => 'event-date',
'compare' => '<',
'value' => $year1,
),
array(
'key' => 'event-date',
'compare' => '>=',
'value' => $year2,
),
);
$twoago = array(
array(
'key' => 'event-date',
'compare' => '<',
'value' => $year2,
),
array(
'key' => 'event-date',
'compare' => '>=',
'value' => $year3,
),
);
$threeago = array(
array(
'key' => 'event-date',
'compare' => '<',
'value' => $year3,
),
array(
'key' => 'event-date',
'compare' => '>=',
'value' => $year4,
),
);
?>
Then:
<?php
$args = array(
'post_type' => 'events-lists',
'meta_key' => 'event-date',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'meta_query' => $threeago,
); ?>
This works fine but it seems to inelegant and needlessly verbose.
Any suggestions on how to tighten this up?
Hi @dtomasch
I believe you can order the posts based on the date picker field. This page should give you more idea about it: https://www.advancedcustomfields.com/resources/orde-posts-by-custom-fields/.
You can also query the post to get only the last four years. Please take a look at this page to learn more about it: https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters.
By combining those queries, you only need to loop the posts and check the event’s year.
I hope this helps 🙂
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Cookie Policy. If you continue to use this site, you consent to our use of cookies.