Where to insert ACF PHP code snippets?

Sorry if this is a dumb question. I’d like to display my CPT on the front end dynamically as label : field value. I know I a workaround is to add a static html label in front of the dynamic field but that’s untidy if there is no data in the field.

I know this can be done the old school way by adding a code snippet to the template file in a classic theme but how is this done with a FSE block theme. i.e. where do I insert the code?

The code from the ACF website is

<?php $field = get_field_object('my_field'); ?>

<?php echo $field['label']; ?>: <?php echo $field['value']; ?>

Hi @slpoty,

Sorry to hear you’re experiencing trouble with this.

You could achieve this, in a simpler way, by using the Cwicly dynamic content.

This way you can display your CPT’s field value, and use the Before Static text feature as follows:

Or is there a reason you don’t wish to do it this way?

Hi, my cpt has 1 required image and 2 optional images. If no optional images are added then a label and fallback image are displayed on the front end. I don’t want to display any fallback images or labels as its messy and leaves stuff in the code.

I’ve seen elsewhere and on the ACF forum that the way to fix this is to add the php code to the template file but that only works for a classic theme.

Hope that makes sense.

You can add the code snippet directly in your template using our Code block.

I personally had to tweak the snippet as follows:

<?php
$field = get_field_object('my_field');
if (is_array($field) && isset($field['label'], $field['value'])) :
    echo esc_html($field['label']) . ': ' . esc_html($field['value']);
endif;
?>

Note: please ensure that you have activated PHP from the Role Editor:

Please don’t hesitate to let me know if you have any other questions.

Awesome, thanks :slight_smile: :slight_smile: