Skip to content

Instantly share code, notes, and snippets.

@vaandefanel
Created July 1, 2025 08:32
Show Gist options
  • Save vaandefanel/4b82013f2b2c082e4160464012c3a632 to your computer and use it in GitHub Desktop.
Save vaandefanel/4b82013f2b2c082e4160464012c3a632 to your computer and use it in GitHub Desktop.
Helper class for ACF and Gutenberg. Get blocks fields by passing block_id or block name and post_id, outside the block.
<?php
class BlockHelper
{
public function getBlockFromPageByName(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) {
acf_setup_meta($block['attrs']['data'], $block['attrs']['id'], true);
$acf_fields=get_fields();
acf_reset_meta($block['attrs']['id']);
return $acf_fields;
}
}
}
return false;
}
//block id example : block_acf-block_6862ace8efff7
public function getBlockFromPageById(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_meta($block['attrs']['data'], $block['attrs']['id'], true);
$acf_fields=get_fields();
acf_reset_meta($block['attrs']['id']);
return $acf_fields;
}
return false;
}
}
@vaandefanel
Copy link
Author

Use:

<?php
 $helper = new BlockHelper();
 return $helper->getBlockFromPageByName($block_type, $post->ID);
 //return $helper->getBlockFromPageById('block_acf-block_6862abe8e85f7', $post->ID);

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