Created
July 16, 2021 20:53
-
-
Save interactiveRob/fd85dfe5e0db638c59cbccf65ea40e75 to your computer and use it in GitHub Desktop.
ACF get fields from Gutenberg block on another post
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 | |
| function rmk_get_block_from_post($post_id = null, $block_name =''){ | |
| $all_blocks = parse_blocks(get_the_content('', false, $post_id)); | |
| //handle global blocks | |
| $ref_blocks = array_filter($all_blocks, function($block){ | |
| return isset($block['attrs']['ref']); | |
| }); | |
| //expand global blocks | |
| $expanded_refs = array_map(function($block){ | |
| $global_block_id = $block['attrs']['ref']; | |
| return parse_blocks(get_the_content('', false, $global_block_id)); | |
| }, $ref_blocks); | |
| $expanded_ref_blocks = array_values($expanded_refs)[0]; | |
| //put expanded globals in the main block array | |
| if(!empty($expanded_ref_blocks)): | |
| $all_blocks = array_merge($all_blocks, $expanded_ref_blocks); | |
| endif; | |
| $selected_blocks = array_filter($all_blocks, function($block) use ($block_name){ | |
| return $block['blockName'] == "acf/{$block_name}"; | |
| }); | |
| if(empty($selected_blocks)) return []; | |
| $selected_block = array_values($selected_blocks)[0]; | |
| if(!isset($selected_block['attrs']['data'])) return []; | |
| acf_setup_meta( $selected_block['attrs']['data'], $selected_block['attrs']['id'], true ); | |
| $fields = get_fields(); | |
| acf_reset_meta( $selected_block['attrs']['id'] ); | |
| return $fields; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment