Home › Forums › Front-end Issues › Query by numeric field and field as title
I need help with a WordPress query to get posts.
I have an ACF-numeric-Field called “year”.
I need a query to get posts who have entered a year, and the year is echoed as title.
Someting like
1925
– Post A
– Post B
– Post D
1926
– Post C
– Post E
This is what I have so far to get posts with a “year” set and ordered by.
<?php
$args = array(
'numberposts' => -1,
'post_type' => 'artikel',
'meta_query' => array(
'relation' => 'AND',
array(
'key' => 'year',
'compare' => 'EXISTS'
),
array(
'key' => 'year',
'value' => 1900,
'type' => 'NUMERIC',
'compare' => '>'
)
)
);
$the_query = new WP_Query( $args );
?>
<?php if( $the_query->have_posts() ): ?>
Can someone help me how to put the year as the title?
Your query should look more like this
$args = array(
'numberposts' => -1,
'post_type' => 'artikel',
'meta_query' => array(
'relation' => 'AND',
'date_clause' => array(
'key' => 'year',
'value' => 1900,
'type' => 'NUMERIC',
'compare' => '>'
)
),
'orderby' => array('date_clause' => 'ASC')
);
You do not need the “EXISTS” meta query since you only want posts that have a value greater than something.
I have also added a “date_clause” for a index so that they can be ordered by this field and added the orderby.
$query = new WP_query($arg);
if ($query->have_posts()) {
$last_post_year = 0; // year of last post shown initialized to zero
while ($query->have_posts()) {
the_post();
$this_post_year = get_field('year');
if ($this_post_year != $last_post_year) {
// this post is in a different year than the last one
echo $year;
}
$last_post_year = $this_post_year; // update last to this
// anything else you want to this post
}
}
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 Privacy Policy. If you continue to use this site, you consent to our use of cookies.