Retrieve image url from ACF field using the parse_blocks() method | Wordpress
How can I retrieve the image URL from an ACF field in Gutenberg blocks using the parse_blocks method?
To retrieve an image URL from an Advanced Custom Fields (ACF) field using the parse_blocks() method in WordPress, you first need to understand how ACF stores image data. If you're using an ACF field of type "Image," it typically returns an array containing information about the image.
When you use the parse_blocks() method, it will return only the image ID. You'll need to retrieve the image URL using that ID. You can use the wp_get_attachment_image_url() method to get the image URL from the image ID.
if(is_page()) { $blocks = parse_blocks( get_the_content() ); //Pass $post_id as a argument if you want other page content foreach($blocks as $block) { if($block['blockName'] == 'acf/block_name') { if (isset($block['attrs']['data']) && is_array($block['attrs']['data'])) { if(isset($block['attrs']['data']['img_field_name']) && $block['attrs']['data']['img_field_name']) { echo wp_get_attachment_image_url($block['attrs']['data']['img_field_name']); } } } } }
Here is a sample example demonstrating how to use the parse_blocks method to retrieve image URLs. In this example, I have preloaded the images for every page's hero block using the wp_head hook. It will add a <link rel="preload" as="image" href="image.png"> tag inside the head section of the HTML document.
add_action( 'wp_head', function(){ if(is_page()) { $blocks = parse_blocks( get_the_content() ); foreach($blocks as $block) { if($block['blockName'] == 'acf/hero-banner') { if (isset($block['attrs']['data']) && is_array($block['attrs']['data'])) { if(isset($block['attrs']['data']['content_img']) && $block['attrs']['data']['content_img']) { echo $block['attrs']['data']['content_img']['url']; echo '<link rel="preload" as="image" href="'.wp_get_attachment_image_url($block['attrs']['data']['content_img']).'" />'; } if(isset($block['attrs']['data']['mobile_image']) && $block['attrs']['data']['mobile_image']) { echo '<link rel="preload" as="image" href="'.wp_get_attachment_image_url($block['attrs']['data']['mobile_image']).'" />'; } } } } } });