Expose a Custom Field in the REST API and Block Editor
Registers a post meta field (a subtitle by default) so it is saved safely, available in the REST API and usable by the block editor and block bindings.
Opens WPIDE on
Code
add_action( 'init', function () {
$post_type = 'post'; // Post type the field belongs to.
$meta_key = 'wpide_subtitle'; // Meta key.
register_post_meta( $post_type, $meta_key, array(
'type' => 'string',
'single' => true,
'default' => '',
'show_in_rest' => true,
'sanitize_callback' => 'sanitize_text_field',
'auth_callback' => function ( $allowed, $key, $post_id ) {
return current_user_can( 'edit_post', $post_id );
},
) );
} );
Notes
Change $meta_key and $post_type. Only users who can edit the post can update the field.
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.