Hello,
I’m creating a block to display a “workshop” custom post type
Each post has a date custom field and I would like to sort them by date
But I can’t get the value of the field in the block render template with a regular WP loop… I tried a query_post and it’s working but then I can’t sort the results by the date field 🙁
here is my code so far, what am I missing… I guess I have to make a second loop to get the post by my date custom field… but can’t find out how!
<?php
$num = get_field('number');
$cat = get_field('cat');
//$date = get_field('date');
if ($num) {
$number = $num;
} else {
$number = '-1';
}
// if ($date) {
// $key = 'date';
// $by = 'meta_value';
// } else {
// $key = null;
// $by = null;
// }
$args = array(
'posts_per_page' => $number,
'post_type' => 'product',
//'meta_key' => $key,
//'orderby' => $by,
'order' => 'DESC',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'terms' => $cat,
'field' => 'slug',
),
),
);
//$products = new WP_Query($args);
$products = query_posts($args);
foreach ($products as $p) :
$date = get_field('date', $p->ID);
?>
<div class="product-block">
<div class="product-figure">
<?php echo get_the_post_thumbnail($p->ID, 'screen-md' ); ?>
</div>
<p class="product-title h3-like"><?php echo get_the_title($p->ID); ?></p>
<p><?php echo $date; ?></p>
</div>
<?php
endforeach;
wp_reset_postdata();
?>
Hey @anybodesign
You should able to do that via get_posts() too.
The most problem you don’t use the proper order value for that.
I think you want to change the ‘order’ like this:
$posts = get_posts([
'post_type' => 'product',
...
'meta_key' => 'your_date_field',
'orderby' => 'meta_value_num',
]);
The key is the meta_value_num when you order by number / date type of fields
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.