Home › Forums › Gutenberg › Get data from block in different page › Reply To: Get data from block in different page
I wanted to post some additional information which would actually assist in how to accomplish the original intent… “how do I query for ACF fields attached to a specific block, by block ID?” I’ve written another function which can do exactly that for you, as long as you know the block ID AND THE POST ID that you’re querying. You can use it very similar to get_field()
, but with a different 3rd (and in this case, required) parameter.
function get_field_from_block( $selector, $post_id, $block_id ) {
// If the post object doesn't even have any blocks, abort early and return false
if ( ! has_blocks( $post_id ) ) {
return false;
}
// Get our blocks from the post content of the post we're interested in
$post_blocks = parse_blocks( get_the_content( '', false, $post_id ) );
// Loop through all the blocks
foreach ( $post_blocks as $block ) {
// Only look at the block if it matches the $block_id
if ( isset( $block['attrs']['id'] ) && $block_id == $block['attrs']['id'] ) {
if ( isset( $block['attrs']['data'][$selector] ) ) {
return $block['attrs']['data'][$selector];
} else {
break; // If we found our block but didn't find the selector, abort the loop
}
}
}
// If we got here, we either didn't find the block by ID or we didn't find the selector by name
return false;
}
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.