Skip to content

Instantly share code, notes, and snippets.

@joseph-farruggio
Last active January 22, 2023 23:12
Show Gist options
  • Save joseph-farruggio/6d62e95c45657ea82e4068e006c44b3c to your computer and use it in GitHub Desktop.
Save joseph-farruggio/6d62e95c45657ea82e4068e006c44b3c to your computer and use it in GitHub Desktop.
Returns a specified field from the parent ACF block.
<?php
/**
* Returns a specified ACF field from a parent block
* @param string $child_id The ID of the child ACF block
* @param string $child_name The name of the child ACF block
* @param string $parent_name The name of the parent ACF block
* @param string $field The name of the parent's custom field to return
* @param boolean $return_first If $field is an array, optionally return the first item.
*/
function get_field_from_parent($child_id, $child_name, $parent_name, $field, $return_first = false) {
global $post;
$parsed_blocks = parse_blocks( $post->post_content );
// Loop through the post content's blocks
foreach( $parsed_blocks as $parsed_block ) {
// Look for the parent block's name
if( $parent_name !== $parsed_block['blockName'] )
continue;
// If the parent block has innerBlocks - it should ¯\_(ツ)_/¯
if ($parsed_block['innerBlocks']) {
// Loop throught the innerBlocks
foreach ($parsed_block['innerBlocks'] as $innerBlock) {
// Look for our child block's name
if( $child_name !== $innerBlock['blockName'] )
continue;
// Look for a match in the block ID of the matching child block's name
if ($innerBlock['attrs']['id'] == $child_id) {
// If the returned field is an array, optionally return the first item
if (is_array($parsed_block['attrs']['data'][$field]) && $return_first) {
return $parsed_block['attrs']['data'][$field][0];
}
// Else, return the field value
return $parsed_block['attrs']['data'][$field];
}
}
}
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment