Skip to content

Instantly share code, notes, and snippets.

@jenssogaard
Created February 22, 2019 21:08
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save jenssogaard/54a1927ecf51c3238bd3eff1dac73114 to your computer and use it in GitHub Desktop.
Save jenssogaard/54a1927ecf51c3238bd3eff1dac73114 to your computer and use it in GitHub Desktop.
Helper class for ACF and Gutenberg. Get blocks fields by passing block_id and post_id.
<?php
namespace JensSogaard;
class BlockHelper
{
/**
* Gets ACF fields for a specific block on a given post
* @author Jens Soegaard <jens@jenssogaard.com>
*/
public function getBlockFromPage(string $block_id, int $post_id)
{
$post = get_post($post_id);
if (!$post) return false;
$blocks = parse_blocks($post->post_content);
foreach($blocks as $block){
if ($block['attrs']['id'] !== $block_id) continue;
acf_setup_postdata($block['attrs']['data'], $block['attrs']['id'], true);
acf_reset_postdata($block['attrs']['id']);
return get_fields();
}
return false;
}
/**
* Return post id by checking for post instance, second POST param post_id (eg. if ACF ajax preview from Gutenberg), third GET page_id (WP preview)
* @author Jens Soegaard <jens@jenssogaard.com>
*/
public function getPostId()
{
if (get_the_ID()) return get_the_ID();
if (isset($_POST['post_id'])) return $_POST['post_id'];
if (isset($_GET['page_id'])) return $_GET['page_id'];
return false;
}
}
@sitesandsuch
Copy link

sitesandsuch commented May 5, 2019

Thanks so much! This lead me into the right direction. Functions have been renamed (5.8.0-RC2):
acf_setup_meta()
acf_reset_meta()

@mentorkadriu
Copy link

mentorkadriu commented Aug 23, 2019

Used a bit different solution:

public function getBlockFromPage(string $block_name, int $post_id)
    {
        $post = get_post($post_id);

        if (!$post) return false;
        $blocks = parse_blocks($post->post_content);

        if ($blocks) {
            foreach ($blocks as $block) {
                if($block['blockName'] == $block_name) {
                    return $block['attrs']['data'];
                }
            }
        }

        return false;
    }

Use:

<?php
  $post_layout = new BlockHelper();
  $post_layout = $post_layout->getBlockFromPage('acf/post-layout', $post->ID); // name of the block
  $post_format = $post_layout['post_format'];// name of the field
?>

@santhudadi
Copy link

@mentorkadriu

I am trying to setup same and return acf field data out of the block.
Do I need to paste this code in functions,.php file or block.php file.

@Mandorlo
Copy link

Mandorlo commented Mar 8, 2022

If you use InnerBlocks, don't forget to look in $block['InnerBlocks']

@Mishkamshka
Copy link

Sorry how do I do this?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment