Last active
September 5, 2023 14:52
-
-
Save lunule/5924435d0530b66a8f073c85f0870c99 to your computer and use it in GitHub Desktop.
[ACF - Get get_field() data while using parse_blocks] #acf #get_field #php #parse_blocks #parse #get #blocks #block #field #fields
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 | |
| /** | |
| * Based on this one: | |
| * https://portalzine.de/dev/php/advanced-custom-fields-get-gutenberg-blocks-data/ | |
| */ | |
| // Parse blocks from post content | |
| $blocks = parse_blocks( $post->post_content ); | |
| $img_Arr = []; | |
| // Loop through the blocks | |
| foreach($blocks as $block) : | |
| // Setup global block post data context | |
| acf_setup_meta( | |
| $block['attrs']['data'], | |
| $block['attrs']['data']['image'], // the last key should match the name of the field you're looking for | |
| true | |
| ); | |
| // Get ACF field | |
| $img_Arr = get_field('image'); | |
| // Restore global context | |
| // before: acf_reset_postdata | |
| acf_reset_meta( $block['attrs']['data']['image'] ); | |
| endforeach; | |
| /* ====================================================================================== */ | |
| /** | |
| * Another example of using acf_setup_meta() | |
| * @here https://github.com/AdvancedCustomFields/acf/issues/654#issuecomment-1244156357 | |
| */ | |
| $field = my_acf_parent_block_field( 'field_name', $context ); | |
| if ( ! function_exists( 'my_acf_parent_block_field' ) ) : | |
| function my_acf_parent_block_field( $field_name, $context ) { | |
| // Get the parent block ACF fields from $context if provided | |
| $context = isset( $context['acf/fields'] ) ? $context['acf/fields'] : array(); | |
| // Get the correct field, depending on the "field_name" or "field_key" is passed | |
| $context_data = acf_setup_meta( $context ); | |
| // Get the field value | |
| $value = isset( $context_data[$field_name] ) ? $context_data[$field_name] : ''; | |
| // Get the field object | |
| $field = get_field_object( $field_name ); | |
| // Get the formatted value if exists | |
| $value = apply_filters( 'acf/format_value', $value, '', $field ); | |
| return $value; | |
| } | |
| endif; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment