Preview image in ACF gutenberg block

1.9k views Asked by At

Is it possible to add an image to the gutenber block preview when using ACF to register the block ?

enter image description here

Here's the code to register the block:

acf_register_block(array(
    'name'              => 'bk-raisons',
    'title'             => __('Les raisons', 'diezel'),
    'description'       => __('Les raisons', 'diezel'),
    'render_callback'   => 'my_acf_block_render_callback',
    'category'          => 'spira-custom',
    'icon'              => 'align-wide',
    'keywords'          => array('bk-raisons'),
));

The preview appears when hovering the block.

Thank you !

1

There are 1 answers

0
Jandon On

I finally found a solution.

I don't know if you use Twig (Timber) or not.

If not check this : https://stackoverflow.com/a/67846162/6696150

For my part with Timber

When you declared your block add example attributes :

$img_quadruple = array(
    'name'              => 'img-quadruple',
    'title'             => __('Quatre images'),
    'title_for_render'  => 'img-quadruple',
    'description'       => __(''),
    'render_callback'   => 'ccn_acf_block_render_callback',
    'category'          => 'imgs',
    'icon'              => '',
    'mode'              => 'edit',
    'keywords'          => array( 'quatre images' ),
    'example'           => array(
        'attributes'        => array(
            'mode' => 'preview',
            'data' => array(
                'preview_image_help' => get_template_directory_uri().'/assets/img/preview/preview_img_quadruple.jpg',
            ),
        )
    )
);

And when your declared your callback :

function ccn_acf_block_render_callback( $block, $content = '', $is_preview = false ) {
    $context = Timber::context();

    // Store block values.
    $context['block'] = $block;

    // Store field values.
    $context['fields'] = get_fields();

    // back-end previews
    if ( $is_preview && ! empty( $block['data'] ) ) {
        echo '<img src="'. $block['data']['preview_image_help'] .'" style="width:100%; height:auto;">';
        return;
    } elseif ( $is_preview ) {
        echo 'Other condition';
        return;
    }

    // Store $is_preview value.
    $context['is_preview'] = $is_preview;

    // Render the block.
    Timber::render('gutenberg/gut_' . strtolower($block['title_for_render']) . '.twig', $context );
}