Archived topic
Placeholder dynamic data
12 replies · Started by Kees on December 28, 2022
Hi,
Is it possible to make a placeholder/fallback for a dynamic field? I have a video in the private data.
Sometimes the field is empty so i would like to show a placeholder or default/fallback text.
How dow we fix this?
Regards,
Niek
Hi Niek,
Yes, it's possible.
1. Give the Headline Block a class of cu-headline
Adding Custom Classes: https://wordpress.com/support/wordpress-editor/adding-additional-css-classes-to-blocks/
2. Add this Snippet:
add_filter('generateblocks_dynamic_content_output', function($content, $attributes, $block){
if ( !is_admin() && ! empty( $attributes['className'] ) && strpos( $attributes['className'], 'cu-headline' ) !== false ) {
if( ! $content ){
$content = 'MY TEXT HERE';
}
}
return $content;
}, 10, 3);
Adding PHP: https://docs.generatepress.com/article/adding-php/#code-snippets
Replace "MY TEXT HERE" with your fallback text.
Hi,
Thanks, but this is not working. I think i did everything right. See video. Does the code needs to be changed?
Sorry, I forgot to mention that you need to use the dynamic settings of GB to make this code work.
Can you remove the dynamic settings from the toolbar? Then, enable the dynamic settings from the Block Setting on the side. This one is from GenerateBlocks.
Let us know how it goes.
Nice, that seems to work. We have several dynamic fields. What is the best way? copy the code and change the name of the function and class?
So, for each heading we need a fallback
You can try to modify the code to something like this:
add_filter('generateblocks_dynamic_content_output', function($content, $attributes, $block){
if ( ! is_admin() && ! $content && ! empty( $attributes['className'] ) ) {
if( strpos( $attributes['className'], 'cu-headline' ) !== false ){
$content = 'MY TEXT HERE';
} else if ( strpos( $attributes['className'], 'cu-headline2' ) !== false ){
$content = 'MY TEXT HERE 2';
} else if ( strpos( $attributes['className'], 'cu-headline3' ) !== false ){
$content = 'MY TEXT HERE 3';
}
}
return $content;
}, 10, 3);
You can copy and paste the else if condition multiple times for each of your dynamic text. You need to have different classes for each.
Thanks, almost there i think. But the output is then always the same: see video.
I see. Can you try a different structure for the Headline classes?
For instance, ab-headline, cd-headline and ef-headline.
Nice, that works. Is that ab- cd- ef- random? or did your search somewhere for that?
It's random. Just checked if strpos is strict comparison. Since ab- cd -ef works, it seems it isn't.
Using different characters for your variables at the start is ideal for the code to work.
Thanks, will try that. For now it is solved.
You're welcome, Niek!
