Support

Account

Home Forums Gutenberg Register block preview image with acf_register_block_type?

Solving

Register block preview image with acf_register_block_type?

  • In WordPress 5.3 you can now see a preview image for the core Gutenberg blocks when you hover over their icons in the top left add block popup. It would be great to be able to set a static image for custom blocks registered with acf_register_block_type. If I add ‘example’ => [] to the block attributes, it will try to generate a preview from my block output via an ajax call, but it’s not super pretty since we have heavy use of animations, SVG’s and other funky layouts on the front-end. Has anyone figured out a way to use static images for these previews?

  • Yes, i would like to “+1” this too.
    It would be a great addition to the ACF blocks.

    Now all blocks EXCEPT the ACF blocks have examples.

  • Also looking forward to this πŸ™‚

  • +1 for this. Yes the β€˜example’ => [] works but just doesn’t render well with the html that doesn’t even try to make it responsive.

    Yes please for an image preview!

  • +1 – This would be awesome. We really need this for our projects.

  • The easiest way I think to do this is to pass the example array to the acf_register_block_type function and include “an additional non-custom-field value” as mentioned in the “Adding block previews πŸŒ„” section of the [function’s docs](https://www.advancedcustomfields.com/resources/acf_register_block_type/).

    In the rendering template, include a conditional to check for the is_example flag and render a screenshot instead of the HTML, if it’s set. The screenshot could be an image, GIF, or even video (probably). See my conclusion after the code examples.

    // init.php
    acf_register_block_type([
    ...
    	'example' => [
    		'attributes' => [
    			'mode' => 'preview',
    			'data' => ['is_example' => true],
    		]
    	]
    ...
    ]);
    // block.php
    if (get_field('is_example')) :
    	/* Render screenshot for example */
    else :
    	/* Render HTML for block */
    endif;

    That’s how I *think* it should work, but I have an issue with get_field not returning data from the example array. Am I missing something? The docs are pretty clear on how to include data for the example render, but it’s not working at all for me. I’m also not seeing any of the data that I’m passing in the example array show up in the $block['data'] array as mentioned in the docs πŸ˜•

  • Just like @phip said, I don’t see any data from the example array passed to my block rendering. Are we missing something?

  • Just a quick update, I’ll link to a comment I found by Eliot on github. https://github.com/AdvancedCustomFields/acf/issues/264#issuecomment-629558291

    Basically says that if you use “get_fields” instead of single “get_field” functions, it won’t pass the data because the name of the fields aren’t declared at that moment in the code execution. You can still pass examples without refactoring your code to use “get_field”, but you have to use the field IDs like so and it will work with “get_fields” :

    
    'example'  => [
        'attributes' => [
            'mode' => 'preview',
            'data' => [
                "field_5efb9b4a86e4d" => "Titre gauche",
                "field_5f29ba5f8e2f1" => "h2",
                "field_5efb9b4a86e4f" => "Sous-titre gauche",
                "field_5efb9b4a86e51" => "<p>Mauris turpis risus scelerisque mollis interdum tincidunt lectus parturient nibh</p>",
                "field_5f08b1ab13927" => ["url" => "http://google.com", "target" => "_blank", "title" => "Lien gauche"],
                "field_5f0c252bdce4e" => 0,
                "field_5f29c57dad9dc" => "text-white",
                "field_5f29c59dad9dd" => "opacity-15",
                "field_5f3a04b753a8d" => "Titre droite",
                "field_5f3a04a953a8c" => "h2",
                "field_5f3a04bd53a8e" => "Sous-titre droite",
                "field_5efb9b4a86e52" => "<p>Mauris turpis risus scelerisque mollis interdum tincidunt lectus parturient nibh</p>",
                "field_5f08b24c905b3" => ["url" => "http://google.com", "target" => "_blank", "title" => "Lien gauche"],
                "field_5f0c2543dce4f" => 0,
                "field_5f29c5dbad9de" => "text-white",
                "field_5f29c5ebad9df" => "opacity-15",
                "is_preview" => 1
            ]
        ]
    ]
    
  • (apologies if this is posted twice, got a bug and not sure if it went through)

    Just a quick update, I’ll link to a comment I found by Eliot on github. https://github.com/AdvancedCustomFields/acf/issues/264#issuecomment-629558291

    Basically says that if you use “get_fields” instead of single “get_field” functions, it won’t pass the data because the name of the fields aren’t declared at that moment in the code execution. You can still pass examples without refactoring your code to use “get_field”, but you have to use the field IDs like so and it will work with “get_fields” :

    
    'example'  => [
        'attributes' => [
            'mode' => 'preview',
            'data' => [
                "field_5efb9b4a86e4d" => "Titre gauche",
                "field_5f29ba5f8e2f1" => "h2",
                "field_5efb9b4a86e4f" => "Sous-titre gauche",
                "field_5efb9b4a86e51" => "<p>Mauris turpis risus scelerisque mollis interdum tincidunt lectus parturient nibh</p>",
                "field_5f08b1ab13927" => ["url" => "http://google.com", "target" => "_blank", "title" => "Lien gauche"],
                "field_5f0c252bdce4e" => 0,
                "field_5f29c57dad9dc" => "text-white",
                "field_5f29c59dad9dd" => "opacity-15",
                "field_5f3a04b753a8d" => "Titre droite",
                "field_5f3a04a953a8c" => "h2",
                "field_5f3a04bd53a8e" => "Sous-titre droite",
                "field_5efb9b4a86e52" => "<p>Mauris turpis risus scelerisque mollis interdum tincidunt lectus parturient nibh</p>",
                "field_5f08b24c905b3" => ["url" => "http://google.com", "target" => "_blank", "title" => "Lien gauche"],
                "field_5f0c2543dce4f" => 0,
                "field_5f29c5dbad9de" => "text-white",
                "field_5f29c5ebad9df" => "opacity-15",
                "is_preview" => 1
            ]
        ]
    ]
    
  • so is this working or not ? i ask because i followed the site example and failed. get_field returns the acf data but if the field is empty there is not default data (from example)

  • I found a workaround since the above solution wasn’t working for me, and is kind of a pain if using get_fields(). Turns out you don’t need to add any custom data to the preview. Turns out when fetching the preview, WordPress includes the fact that it is a preview within the $_POST params.

    So you can just set up the example like this when registering the block

    
    'example'           => [
      'attributes'  => [
        'mode'  => 'preview',
        'data'  => [],
      ]
    ],
    

    Then when rendering the content check if it is a preview like this

    
    if( ! empty( $_POST['query']['preview'] ) :
      /* Render screenshot for example */
    else :
      /* Render HTML for block */
    endif;
    
  • 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.

        acf_register_block_type(
        	array(
    	        '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',
    	                )
    	            )
    	        )
    	    )
    	);
    

    WARNING:
    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>
    			</div>
    			<?
    			
    		endif;
    

    Hope this helps!

  • Thank you @paulgagu this worked for me too!

  • Hi, with this solution often the WYSIWYG editor breaks when you hover over the block inserter elements. I have seen this in multiple sites that use this technique.

    It seems that the ACF code breaks whenever the preview is not yet fully loaded.

    A native acf solution for this would be highly appreciated.

    You would like clients to see a preview image of what they are actually going to insert. The current idea of an actual render of the component seems like a nice idea but requires a lot more work from the developer and is not worth it. Adding an image would be such a simple solution.

  • @geometry dash lite Thank you so much; this is working well @paulgagu

  • @rrmeines if your preview image is a small image (maybe low res) you wont have any problem with breaking the editor, I use it in dozens of sites (one has 53 ACF blocks) without problems. Sure a native solution from ACF is more than welcome.

  • @paulgagu do you have a working example with the new block.json since version 6.0? I use this but when I for example try the following code and have the hallo.jpg inside the same folder as the block.json, it doesnt work :/:

    "example": {
        "attributes": {
            "data": {
                "preview_image_help" : "../accordion/hallo.jpg"
            }
        }
    }
  • @nikolaimoskito did you try an absolute path to the image?

    “example”: {
    “attributes”: {
    “data”: {
    “preview_image_help” : “https://domain.com/wp-content/themes/your-theme/any-folder/accordion/hallo.jpg&#8221;
    }
    }
    }

  • @paulgagu I’m trying that and getting an error.

Viewing 25 posts - 1 through 25 (of 31 total)

The topic ‘Register block preview image with acf_register_block_type?’ is closed to new replies.