Home › Forums › General Issues › ACF Pro 6 Block IDs as Attribute Not Working › Reply To: ACF Pro 6 Block IDs as Attribute Not Working
ACF removes attributes added directly to the normal attribute scope. I’m guessing it happens if it isn’t created in the field group.
Below code adds the attribute blockId
to the data scope of the block, so instead og getting from $block['blockId']
you can use $block['data']['blockId']
Hook is wp_insert_post_data
You can probably do without the placeholder array, but I kept for debugging purposes.
add_filter( 'wp_insert_post_data', function ( $data, $postarr ) {
// Blocks to add attribute
$blocks_check = ['acf/my-block-name','core/paragraph', 'core/heading'];
// Get saved page blocks
$blocks_data = parse_blocks( wp_unslash( $data['post_content'] ) );
// Placeholder array
$blocks_changed = array();
// Loop through blocks
foreach ( $blocks_data as $block ) {
// Check if block is in array of blocks to add attribute
if (!isset($block['blockName']) || !in_array($block['blockName'], $blocks_check)) {
$blocks_changed[] = $block;
continue;
}
// Add attributes
$block_changed = $block;
$block_changed['attrs']['data']['blockId'] = ( !empty( $block['attrs']['data']['blockId'] ) ? $block['attrs']['data']['blockId'] : 'id_' . uniqid() );
$blocks_changed[] = $block_changed;
}
//Add to error log
//error_log( print_r( $blocks_changed, true ) );
// Update post content
$data['post_content'] = serialize_blocks( $blocks_changed );
// Return data
return $data;
}, 99, 2);
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.