Forked from jenssogaard/ACF Gutenberg get block fields
Last active
January 13, 2020 10:18
-
-
Save aaronsummers/c1d58b4966549046de474e40e3a2f8aa 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.
This file contains 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 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; | |
} | |
/** | |
* 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; | |
} | |
} |
This file contains 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 | |
$post_layout = new BlockHelper(); | |
$post_layout = $post_layout->getBlockFromPage('acf/post-header', get_the_ID()); // name of the block array() | |
$post_format = $post_layout['hero_image'];// name of the field |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment