I have a custom post type called project
. Since each project can have multiple happening dates, I created a repeater field date-and-time named dates
with a sub-field named date
.
I would like to display all the posts in a page like following (sorted by acf sub field date
):
project A: 10th march
project B: 17th march
project A: 21st march
project C: 30th march
project A: 5th april
project B: 12th april
and so on...
How can I achieve this?
My Answer:
You can achieve this by using the WP_Query class in WordPress along with the meta_query parameter to query posts based on the ACF repeater field. Here's an example code snippet to achieve this:
php
$args = array(
'post_type' => 'project',
'posts_per_page' => -1,
'meta_key' => 'dates_0_date', // assuming 'dates' is the repeater field key
'orderby' => 'meta_value',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'dates_0_date', // assuming 'date' is the sub-field key
'compare' => 'EXISTS'
)
)
);
$query = new WP_Query($args);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
// Display your project post here
echo get_the_title() . ': ' . get_field('dates_0_date') . '
';
}
}
wp_reset_postdata();
In this code snippet, we are querying all posts of the 'project' custom post type and sorting them by the 'dates_0_date' sub-field of the 'dates' repeater field in ascending order. We then loop through the posts and display the project title along with the date from the repeater field.
Make sure to replace 'dates_0_date' and 'dates' with the actual ACF field keys you have set up in your project.
Rate this post
4 of 5 based on 2169 votesComments