Skip to content

Instantly share code, notes, and snippets.

@davidallenlewis
Last active March 3, 2019 15:24
Show Gist options
  • Save davidallenlewis/cc07f659b77c57559bcb1915b20c7af6 to your computer and use it in GitHub Desktop.
Save davidallenlewis/cc07f659b77c57559bcb1915b20c7af6 to your computer and use it in GitHub Desktop.
Get ACF Block fields outside block template
<?php
// *******************************
// Get ACF block fields outside block templates
// -------------------------------
function get_block_field( $field_id, $post_id = '' ) {
// Get current post ID if post_id arg isn't passed
$post_id = $post_id ? $post_id : get_the_ID();
// Get the post object
$post = get_post( $post_id );
if ( has_blocks( $post->post_content ) ) {
// Parse the post content
$blocks = parse_blocks( $post->post_content );
// Look for keys that contain the ACF field ID we're looking for
$result = array_get_values_by_key_search( $blocks , $field_id );
return $result;
}
return false;
}
// *******************************
// HELPER: Array key search to return values
// -------------------------------
function array_get_values_by_key_search( $array , $field_id ) {
$result = array();
foreach( $array as $key => $value ) {
if( is_array( $value ) ) {
$result = $result + array_get_values_by_key_search( $value , $field_id );
} elseif ( strpos( $key , $field_id ) !== false ) {
$result[ $key ] = $value;
}
}
return $result;
}
@davidallenlewis
Copy link
Author

davidallenlewis commented Mar 3, 2019

This only returns strings not arrays. So it's not super flexible but works for what I needed. I wanted a "HTML Anchor" clone field on all my blocks and then grab all the anchors for a page in page.php template. The only option seems to be to scrape post_content since ACF Blocks doesn't save anything to postmeta. And using 'supports' => anchor didn't help as that only seems to work for the core/heading block. Nothing seems to get saved to the database when using the Gutenberg anchor field on other block types so I just used an ACF field.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment