Archived topic
Display ACF date field in Query Loop
3 replies · Started by Tina on October 21, 2022
Hi,
I have a tricky problem that I was hoping you could give me some guidance on.
I want to display a ACF date field in a GP Query Loop. Using Dynamic Data -> Post Meta does not work unfortunately, because ACF stores dates as Ymd in the database and this is also how Dynamic Data retrieves and displays it, however I need m.d.Y
Solution I've tried but didn't work is with this shortcode:
function display_date() {
ob_start();
global $post;
?>
<div class="event-date">
<?php the_field('sort-datum', $post->id ) ?>
</div>
<?php
return ob_get_clean();
}
add_shortcode( 'display_date','display_date' );
This just prints the date field of the first post in the loop for all posts. It seems like '$post-id' is not grabbing the right id.
My problem seems to be similar to this question. Here, the suggested solution is to use render_block() to make get_the_id() grab the correct value.
This is where I am stuck: I tried to adapt the solution proposed here , but I can't get it to work.
This is what I have:
function gt_rerender_container_add_id( $block_content, $block ) {
if ( ! is_admin() && ! empty( $block['attrs']['className'] ) && 'add-dynamic-id' === $block['attrs']['className'] ) {
$my_block = 'class="gb-headline gb-headline-d9ae39f0 gb-headline-text event-date-id';
$id = get_the_ID( $post-> id);
$event_date = get_field('sort-date', $id);
$my_id = 'event-'.$event_date;
$my_replace = 'class="gb-headline gb-headline-d9ae39f0 gb-headline-text event-date-id">Content'.$event_date;
$new_content = str_replace($my_block, $my_replace, $block_content);
return $new_content;
}
return $block_content;
}
add_filter( 'render_block', 'gt_rerender_container_add_id', 10, 2 );
The block I inserted into the Query Loop Post Template is just a GP Headline block turned to a div with content 'Content'.
It's not doing anything, which means there's probably something basic I'm missing. Can you point me in the right direction?
Thank you!
Hi Tina,
Give the headline block a CSS class, eg. event_date, then you can use the render_block filter below:
add_filter( 'render_block', function( $block_content, $block) {
if ( ! empty( $block['attrs']['className'] ) && strpos( $block['attrs']['className'], 'event_date') !== false ) {
$date = strtotime( get_field('sort-datum') );
$block_content = wp_date( "m.d.Y", $date );
}
return $block_content;
}, 10, 2 );
Hi Ying, amazing, works like a charm! Thank you so much! This helps me out a lot.
You are welcome, glad to help :)