Home Forums Gutenberg Register block preview image with acf_register_block_type? Reply To: Register block preview image with acf_register_block_type?

  • Hi everyone,
    After reading a zillion of posts on all over internet about how to add an image as preview in custom ACF Blocks and getting nowhere I found myself a solution:

    1) You need to add ‘example’ when you register your ACF block, add “mode” attribute as “preview” and any specific data you want to pass.

    	        'name' => 'name-of-block',
    	        'title' => __('Your Title'),
    	        'description' => __('Your description'),
    	        'post_types' => array('page'),
    	        'category' => 'common',
    	        'render_template' => '../your/path/block_template.php', // your template
    	        'icon' => '', // svg code for icon
    	        'keywords' => array('Keyword', 'another'),
    	        'example'  => array(
    	            'attributes' => array(
    	                'mode' => 'preview',
    	                'data' => array(
    	                	'preview_image_help' => '../your/dir/block-image-preview.jpg',

    The field “preview_image_help” needs to be a unique name, and CAN NOT EXIST in the block fields.

    The block will be render in preview mode in 2 places, the editor and the block inserter preview, (when you hover on the name of the block).
    When renders in the editor it will have all the fields you define in the block.
    When renders in the inserter preview will have only the field “preview_image_help”.

    2) Now the render part(in your template), check for the unique field and you will know where the render is taking place:

    	    if( isset( $block['data']['preview_image_help'] )  ) :    /* rendering in inserter preview  */
    			echo '<img src="'. $block['data']['preview_image_help'] .'" style="width:100%; height:auto;">';
    		else : /* rendering in editor body */
    			$text   = get_field('text') ?: 'Default text ...';
    			$author = get_field('author') ?: 'Author name';
    			$title  = get_field('title');
    			<div class="my_class">
    				<span class="class-title"><?php echo $title; ?></span>
    				<span class="class-text"><?php echo $text; ?></span>
    				<span class="class-author"><?php echo $author; ?></span>

    Hope this helps!