Last active
March 3, 2019 15:24
-
-
Save davidallenlewis/cc07f659b77c57559bcb1915b20c7af6 to your computer and use it in GitHub Desktop.
Get ACF Block fields outside block template
This file contains 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 | |
// ******************************* | |
// 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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.