ACF Custom Fields in FanCoolo WP Blocks with Conditional Rendering
This short video shows how to use an Advanced Custom Fields (ACF) meta box field inside a FanCoolo WP block. We take the PHP code ACF generates for a text field, wrap it in a FanCoolo block, and add the block to the Single Posts template. The block only renders when the field has a value, so posts without one don't get empty markup on the front end.
Create the ACF field
In ACF → Field Groups, we edit a field group called Post that has one field:
- Field Type: Text
- Field Label: Extra field
- Field Name:
extra_field
ACF can copy the PHP code for a field to your clipboard (you'll see the Copied code to clipboard! notice). We copy that code and use it in the block.
Build the block in FanCoolo WP
- In FanCoolo WP, open Blocks and select the block, here named Extra field, with the Category set to Text.
- On the Content tab, paste the field code and wrap the output in a
divthat usesget_block_wrapper_attributes():
<?php if ( $extra_field = get_field( 'extra_field' ) ) : ?>
<div <?php echo get_block_wrapper_attributes(); ?>>
<?php echo esc_html( $extra_field ); ?>
</div>
<?php endif; ?>
We keep the wrapper attributes on purpose. That's how your styles, classes and other attributes from the editor show up on the block.
- On the Style tab, add some basic CSS so the block is easy to see:
.wp-block-fancoolo-extra-field {
background: lime;
padding: 2rem;
}
- Click Save.
Add the block to the Single Posts template
- Go to Appearance → Editor → Templates and open the Single Posts template.
- Insert the Extra field block. A live preview shows up right away in the Template Editor.
- Save the template.
Set the value on a post
Open any post in the editor. If the Extra field meta box is empty, the block doesn't render. Type a value, save, and reload the post. The block now shows up with the value inside it and the styles applied.
The if check does this work. The code checks whether the field has a value, and only then outputs the block wrapper and the content. You can add the block to a template once, and posts without the field stay clean.
Get FanCoolo WP → dplugins.com