Set preview image for custom gutenberg block in wordpress


How to set a preview image for custom blocks in WordPress using acf_register_block_type?

After thorough research, I discovered a method that proved effective for me, realizing that all of you made mistakes in this matter.

✅ Solution:

Add image tag in gutenberg_preview when registering your block in acf_register_block

'gutenberg_preview' => __('<img src="https://via.placeholder.com/480X320">')

Subsequently, you can retrieve the value of "gutenberg_preview" as a field in your template using the_field('gutenberg_preview').
acf_register_block(array(
  'name'		=> 'Buggerspot Block',
  'title'		=> __('Buggerspot Block'),
  'description'		=> __('Buggerspot block.'),
  'render_callback'	=> 'bs_acf_block_render_callback',
  'category'		=> 'buggerspot-custom-blocks',
  'icon'		=> 'admin-comments',
  'keywords'		=> array( 'Bugger', 'spot', 'Buggerspot' ),
  'mode' => 'auto',

  // Set Preview Image To Your Custom Block
  'example'  => array(
    'attributes' => array(
      'mode' => 'preview', // You must set mode as preview
      'data' => array(
        'gutenberg_preview' => __('<img src="https://via.placeholder.com/480X320">'),
      ),
    )
  ),

  'render_template'   => 'templates/blocks/buggerspot-block.php',
));
Once you have completed that step, you can render the image within your template, which will designate it as the preview image of the block. To prevent rendering an empty div in the frontend, you can use the (is_admin) condition to only render the div in the backend editor.
<!-- Block Preview Image -->
<?php if (is_admin()) { ?> 
	<div data="gutenberg-preview-img"><?php the_field('gutenberg_preview'); ?></div>
<?php } ?>



Thank You!