Make a Custom Field Usable in Blocks
Registers a custom field (such as a subtitle) with the REST API so it can be connected to Paragraph or Heading blocks through Block Bindings and edited right in the block.
Opens WPIDE on
Code
// Post type and custom field name.
$wpide_bound_post_type = 'post';
$wpide_bound_meta_key = 'subtitle';
add_action( 'init', function () use ( $wpide_bound_post_type, $wpide_bound_meta_key ) {
register_post_meta( $wpide_bound_post_type, $wpide_bound_meta_key, array(
'type' => 'string',
'single' => true,
'show_in_rest' => true,
'default' => '',
'sanitize_callback' => 'sanitize_text_field',
'label' => ucfirst( str_replace( array( '-', '_' ), ' ', $wpide_bound_meta_key ) ),
'auth_callback' => function ( $allowed, $meta_key, $post_id ) {
return current_user_can( 'edit_post', $post_id );
},
) );
} );
Notes
Requires WordPress 6.5 or newer. Bind it with {"metadata":{"bindings":{"content":{"source":"core/post-meta","args":{"key":"subtitle"}}}}}. Change the post type and field name at the top.
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.