Advanced Custom Fields – Free Your Gutenberg Blocks Data

Updated 25.03. : Some function names changed in the latest beta version.

IN BETA

ACF 5.8 Beta introduced an easy way to create your custom Gutenberg blocks. I am already using it heavily for a current project, to easily organize content and media assets.

Really powerful, when combined with Timber as well, which has been the foundation of many of my themes for years now ;)

ORGANIZE YOURSELF

Organizing data using ACF is nice, but sometimes you seek access to that saved block data directly. I hate it when I am confined to boundaries and the data flow is restricted or hidden. I need things to be accessible to choose the creative flow myself.

SIMPLE EXAMPLE

  1. // Parse blocks from post content
  2. $blocks  = parse_blocks($your_post_content);
  3. $collect = array();
  4.  
  5. // Loop through the blocks
  6. foreach($blocks as $block){
  7.  
  8. //Setup global block post data context
  9. // before: acf_setup_postdata
  10. acf_setup_meta( $block['attrs']['data'], $block['attrs']['id'], true );
  11.  
  12. // Get ACF fields
  13. $fields = get_fields();
  14.  
  15. // I am using this to organize my assets.
  16. // Each block of mine has a unique identifier as its first field:
  17. // $uid = $block['attrs']['data'][array_keys($block['attrs']['data'])[0]]
  18. // I would do:
  19. // $collect[$uid] = $fields;
  20.  
  21. // Collection of fields using the block id.
  22. $collect[$block['attrs']['id']] = $fields;
  23.  
  24. // Restore global context
  25. // before: acf_reset_postdata
  26. acf_reset_meta( $block['attrs']['id'] );
  27.  
  28. }

There you go, enjoy some free block data :)

I was a big skeptic, when it comes to WordPress and the new Gutenberg editor, but combined with ACF + Timber its pure magic :) Looking forward to things to come!

Cheers
Alex

Enjoy coding …

Extended example:

  1. $collect = [];
  2. $blocks = parse_blocks($your->post_content);   
  3.                
  4. foreach($blocks as $block){
  5.                
  6.         if( isset($block['attrs']['data']) && !empty($block['attrs']['data'][array_keys($block['attrs']['data'])[0]])){
  7.                                                                
  8.                 acf_setup_meta( $block['attrs']['data'], $block['attrs']['id'], true );
  9.                        
  10.                 $fields = get_fields();
  11.                        
  12.                  acf_reset_meta( $block['attrs']['id'] );
  13.                                
  14.                 $collect[$block['attrs']['data'][array_keys($block['attrs']['data'])[0]]] = array('render'      =>      render_block( $block ),
  15.                                                                                                                                                                  'field'        =>      $fields,                                                                                                                                                                                       
  16.                                                                                                                                                                   'block'       =>      $block
  17.                                                                                                                                                                 );
  18.         }else{
  19.           $collect['main'] .= render_block( $block );
  20. }
  21. }

 

The $collect array will hold all data, including all ACF fields. You will have full access to any field, including repeater fields. The $collect[‘main’] will just collect the standard post content.

Alex

I am a full-stack developer. I love programming,  design and know my way around server architecture as well.  I would never feel complete, with one of these missing. I have a broad range of interests, that’s why I constantly dive into new technologies and expand my knowledge where ever required. Technologies are evolving fast and I enjoy using the latest. Apart from that, I am a peace loving guy who tries to have people around him that think the same.  I truly believe in the principle: “If you help someone, someone will help you, when you need it."

View Comments

      • Thanks! I understand. Seems last update broke "acf_setup_postdata"... We'll need to find another way...

        • Hi,
          function names changed in the latest version.

          // Setup postdata allowing get_field() to work.
          acf_setup_meta( $block['data'], $block['id'], true );

          // Reset postdata.
          acf_reset_meta( $block['id'] );

          The relevant reference code, can be found in pro/blocks.php

          Regards
          Alex

  • Great article Alex, helped me a lot!

    I need to update a custom field inside a specific block. Do you know how update a field value inside that 'acf_setup_meta'??

    I tried using the 'update_field' function, but it saves the field on the post itself, not the block :(

    • Hi Carlos,
      Take a look at the pro/blocks.php. Block content is saved within the post_content.
      acf_parse_save_blocks & acf_parse_save_blocks_callback handle the block comment replacement.
      It should be a matter of getting the current post content, replacing the target block comment and saving it again.
      If I have some time tomorrow, I will take a closer look.
      Cheers
      Alex

  • Hi Alex

    Thanks for taking a stab at this. Don't know why this have to be this difficult.

    I'm trying to grab a field within a repeater from another block, but still on the same page.

    I'm simply trying to output the titles of each field in a repeater from a different block.

    How do I do that?

    Thanks SO much for any assistance you can throw my way.

    • Hi Jake,
      will whip up an example, when I have the time tomorrow.

      Cheers
      Alex

      • Hey Alex

        Don't mean to be pushy, but did you happen to figure out something? No worries if not.

        • Hey Jake,
          have not forgotten about you. Had no time to do it yet, but its on my agenda. Hope to find some time today or tomorrow.
          Later
          Alex

        • Added an extended example above. I am using the same setup on a client website to pull in repeater field data.
          Cheers
          Alex

          • That's very nice of you, thanks a lot.
            Help a noob out, how do I make use of it?
            Do I var_dump($collect) to output the array? If so, that just does array(0) { }

          • Have you passed in the correct post_content ?
            $your->post_content is just a placeholder!

  • I understand how the basis of this works. I changed the parse_blocks to have my post info in it. BUT it is throwing an error on page:

    Warning: key() expects parameter 1 to be array, null given

    Any help would be appreciated.

    • Hi Chad,
      parse_blocks parses the post content. So $post->post_content or $post['post_content'], depending on the way your posts or post have been queried.

  • We have created a custom ACF block with title and description.
    How do I display the info on another page like home when needed as a featured content.

    Where to add the above code to functions.php file or as a plugin?

    When we call the acf field, How do i call the field using this code.

    Sorry as this topic sound bit advanced to me but i needed to achieve the output.

    • All depends, the above code only extracts the raw data.

      Including the data from a post / page or other post_type into your frontpage is similar, but also more involved and nothing generic. If you need help to integrate something like that, we can arrange a meet and greet on Skype to talk this through.

      Regards
      Alex

Recent Posts

Particle Network Animations in Javascript

What are particle animations? Particle network animations in JavaScript typically involve creating visual representations of… Read More

2 days ago

B&B / Hotel Booking Solutions for WordPress | 2024

BOOKING SOLUTIONS 202x This is my take on a subset of booking, appointment, PMS or… Read More

1 month ago

WordPress Cron + WP-CLI + Ntfy

THE GOAL Create a system cron for WordPress, that is accessible and can be easily… Read More

2 months ago

2024 is here and now :)

2024, what's cooking? Slowly getting into the 2024 spirit. 3 projects coming to a close… Read More

4 months ago

2023 ends and whats next !

Short look back at 2023 This has been a busy and interesting year. I am… Read More

4 months ago

cubicFUSION Grid Tweaker – Elementor Grid made easy.

Elementor Pro provides grid containers as an experimental feature. The options provided are limited, when… Read More

5 months ago