-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use: