Use ACF Fields in Core Blocks With Block Bindings
Registers an "ACF field" block bindings source, so paragraph, heading, button and image blocks can show ACF values without a custom block (WordPress 6.5+).
Opens WPIDE on
Code
add_action( 'init', function () {
if ( ! function_exists( 'register_block_bindings_source' ) ) {
return;
}
register_block_bindings_source( 'wpide/acf', array(
'label' => 'ACF field',
'uses_context' => array( 'postId', 'postType' ),
'get_value_callback' => function ( $source_args, $block_instance, $attribute_name ) {
$key = isset( $source_args['key'] ) ? sanitize_key( $source_args['key'] ) : '';
$post_id = isset( $block_instance->context['postId'] ) ? (int) $block_instance->context['postId'] : get_the_ID();
if ( '' === $key || '_' === $key[0] || ! $post_id || ! function_exists( 'get_field' ) || ( ! is_post_publicly_viewable( $post_id ) && ! current_user_can( 'read_post', $post_id ) ) ) {
return null;
}
$value = get_field( $key, $post_id );
if ( is_array( $value ) ) {
$value = $value['url'] ?? ( $value['label'] ?? '' );
}
if ( ! is_scalar( $value ) ) {
return null;
}
return in_array( $attribute_name, array( 'url', 'href' ), true ) ? esc_url( (string) $value ) : esc_html( (string) $value );
},
) );
} );
Notes
Bind in the Code editor, e.g. "metadata":{"bindings":{"content":{"source":"wpide/acf","args":{"key":"subtitle"}}}}. Fields starting with an underscore are never exposed.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.