Skip to content

Instantly share code, notes, and snippets.

@CreativeDive
Last active July 4, 2022 10:01
Show Gist options
  • Save CreativeDive/98e310d7f3f27f76306f99a832686aab to your computer and use it in GitHub Desktop.
Save CreativeDive/98e310d7f3f27f76306f99a832686aab to your computer and use it in GitHub Desktop.
Possible solution to get the ACF field values by passing the field key, if we want to use the field data from the parent block inside a child block.
<?php
/*
* Example
*/
$my_acf_field = get_parent_block_acf_field( $context, 'field_5d4a9875f0c8d' );
$my_acf_field_2 = get_parent_block_acf_field( $context, 'field_622746ee08ac6' );
if( $my_acf_field ) {
echo 'The field from the parent block is active.';
}
/*
* Pass ACF field data from parent block to innerBlock childs using "usesContext": ["acf/fields"] via block.json file
*/
if ( ! function_exists( 'get_parent_block_acf_field' ) ) :
function get_parent_block_acf_field( $fields, $field_key = '' ) {
// Get the parent block ACF fields from $context if provided
$fields = isset( $fields['acf/fields'] ) ? $fields['acf/fields'] : array();
// Check if the field key exists (used in the block editor)
$field = isset( $fields[$field_key] ) ? $fields[$field_key] : '';
if( $field ) {
return $field;
}
/*
* Collect all fields
*/
$keys = array();
foreach( $fields as $key => $value ) {
// Check for nested field keys
if( strpos($key, 'field_') !== false && is_array( $value ) ) {
foreach( $value as $sub_array_key => $sub_array_value ) {
// Remove the prefixed clone field key, to provide the correct field key
$sub_array_key = str_replace( $key . '_', '', $sub_array_key );
$keys[$sub_array_key] = $sub_array_value;
}
} else {
$keys[$key] = $value;
}
}
/*
* Get / return the ACF field value by field key
*/
$field = isset( $keys[$field_key] ) ? $keys[$field_key] : '';
if( $field ) {
// Return the field value if exists
return $field;
}
// Check all ACF fields
foreach( $keys as $key => $value ) {
// Check if a field key value contains the searched field key
if( $value === $field_key ) {
// Remove the underscore from the ACF field name
$key = ltrim( $key, '_' );
// Get the ACF field by field name
$field = isset( $fields[$key] ) ? $fields[$key] : '';
if( $field ) {
// Return the field value if exists
return $field;
}
}
}
}
endif;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment