Archived topic
Formatting ACF date output in Post Query
5 replies · Started by Alessandro on December 9, 2022
Hi, I'm trying to show custom dates for posts in a post query block. They are regular WordPress posts, but with a date field added via ACF.
If I use the post query meta fields I can get the date to display, but only in the generic database format (e.g. 20221209) which is not really usable. I tried creating a shortcode instead, but I can't get that to output anything at all.
What would be the best way to proceed?
Hi there,
GenerateBlocks Pro supports some of the more advanced options of ACF, including the date picker. So thats one solution.
Without GB Pro you would need some function, i found this:
That shortcode James provided worked when i just tested it.
EDIT - Question - is this in a Query Loop block ?
Hi David, it is a query loop block, yes.
Aah ok. So GenerateBlocks Pro will handle that out of the box.
The alternative is slightly more complicated as the block editor won't parse shortcodes in Query Loops.
So instead you would have to do something more complex:
1. Add a Headline block for where you want the date displayed.
1.1 Add some static text eg. date. This will be the $string to replace
1.2 DO NOT activate dynamic data
1.3 In Advanced > Additional CSS Class(es) add a CSS class eg. show-date this will be the $class we use to find this block.
2. Now you can use this PHP Snippet to render a different output for that block:
add_filter( 'render_block', function( $block_content, $block ) {
$field_name = 'date_field'; // ACF field name
$postId = false;
$format = 'M l, Y'; // date format
$class = 'show-date'; // Additional CSS Class on block to find
$string = 'date'; // string of text to replace with date
$date = get_field( $field_name , $postId, $format );
if (
!is_admin()
&& ! empty( $block['attrs']['className'] )
&& $class === $block['attrs']['className']
){
$block_content = str_replace( $string , $date , $block_content );
}
return $block_content;
}, 10, 2 );
Thanks David, that did it! For some reason the date format in that PHP gets overridden by the format settings in ACF, but that's a plus in my book.
To be honest i wasn't sure what it was doing there or the $post_id. I must have a readup
Glad to hear thats working :)