Detect Preview Mode in ACF Block Templates

Use the $is_preview variable to render different output in the editor vs the front end.

php blocks
|

Use the $is_preview variable to render different output in the editor vs the front end.

ACF passes an $is_preview variable to your block render template. Use it to show simplified or placeholder content in the editor:

<?php
/**
 * Google Map Block Template.
 *
 * @param array $block The block settings and attributes.
 * @param bool  $is_preview True when in the editor.
 */
$location = get_field( 'location' );
$api_key  = get_field( 'google_maps_api_key', 'option' );

if ( $is_preview ) : ?>
    <div class="map-placeholder" style="background: #e5e7eb; padding: 2rem; text-align: center; border-radius: 0.5rem;">
        <p><strong>Google Map</strong></p>
        <?php if ( $location ) : ?>
            <p><?php echo esc_html( $location['address'] ); ?></p>
        <?php else : ?>
            <p><em>Select a location in the block settings.</em></p>
        <?php endif; ?>
    </div>
<?php else : ?>
    <?php if ( $location ) : ?>
        <div class="acf-map" data-lat="<?php echo esc_attr( $location['lat'] ); ?>" data-lng="<?php echo esc_attr( $location['lng'] ); ?>">
            <!-- Full interactive map renders here -->
        </div>
    <?php endif; ?>
<?php endif; ?>

Show a message when required fields are empty:

<?php
$title = get_field( 'title' );
$image = get_field( 'background_image' );

if ( ! $title && $is_preview ) : ?>
    <div style="padding: 2rem; background: #fef3cd; border: 1px solid #ffc107; border-radius: 0.5rem;">
        <p><strong>Hero Block:</strong> Please add a title to see the preview.</p>
    </div>
    <?php return;
endif;
?>

<!-- Normal block output -->

You can also access $is_preview via the $block array:

<?php
$is_editor = $block['is_preview'] ?? false;

Related Snippets

Stay Updated

Get ACF tips and new extensions in your inbox

No spam. Unsubscribe anytime.