Archived topic
Dynamic Data
16 replies · Started by Cris on December 14, 2022
Hello
I am creating a page to display custom fields made with ACF. I use the dynamic options of the Headline block to show the names of those custom fields but in another block I want to also show the field label so that, in case there is no data, it is not displayed. Can you tell me how can I do it please?
Hi Cris,
I would recommend using a static headline to show the label.
Then add a CSS class to the static headline, eg.hide-when-empty and the below PHP snippet, when the post meta field is empty, the static headline will not appear. Please replace the post_meta_field_name with your post meta field name.
add_filter( 'render_block', function( $block_content, $block ) {
if ( ! empty( $block['attrs']['className'] ) && strpos( $block['attrs']['className'], 'hide-when-empty' ) !== false && empty (get_field('post_meta_field_name'))){
$block_content = "";
}
return $block_content;
}, 10, 2 );
Adding PHP: https://docs.generatepress.com/article/adding-php/
Thanks Ying!
It works perfect but I want to make it for 8 different field labels. Do I repeat the process for each of them or is there another way?
Hi there,
is this in a GP Element ?
Hi David,
Yes, this is a Block Element of GP
In the GP Element the Container Block has a special option called: REMOVE CONTAINER CONDITION in its Layout Settings.
You can set it to No Post Meta and add you ACF Field name. Then use that as a wrapper for your Label and Field.
That works great! I could even put anything inside the block and it would still disappear.
Thanks a lot, David!
One more thing:
One of the custom fields contains emails and when displayed I would like it to do a "mailto:"
It could be done?
Try this PHP Snippet:
function db_rerender_email_url( $block_content, $block ) {
if(!is_admin()){
if (
! empty( $block['attrs']['className'] )
&& 'is-email' === $block['attrs']['className']
) {
$my_search='href="';
$my_replace='href="mailto:';
$new_content = str_replace($my_search, $my_replace, $block_content);
return $new_content;
}
}
return $block_content;
}
add_filter( 'render_block', 'db_rerender_email_url', 10, 2 );
And the block that has the email field give it a class of is-email
It does not work
Did you give the block the class of is-email ?
Yes, I tried in the container block and in the headline block where the meta field is
Can i see the site where this meta is displayed?
okay
I'll send you a link in private
So that custom field you need to also set it as the Link Source. As the snippet above searches for the href in the <a> and currently you're just outputting it as static text.