Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.