I have a custom meta box for saving values from two input fields into a single post meta field.
The data is saved serialized in the DB:
get_post_meta( $post->ID, '_custom_key', true )
will return:
a:2:{s:5:"email";s:10:"[email protected]";s:6:"number";i:15;}
Now, with Gutenberg, I want to move that whole custom meta box into a separate sidebar plugin. So in order to do this, first, I had to add the __back_compat_meta_box
argument when adding the meta box, so it won't appear in Sidebar -> Settings -> Document
anymore:
add_meta_box(
'options',
'Options',
[ $this, 'renderOptionsBox' ],
[ 'post', 'page', 'attachement' ], // the meta field is registered for multiple post types
'side',
'high',
[ '__back_compat_meta_box' => true ]
);
For the meta field (_custom_key
) to work with the block editor, it has to be registered using the register_meta
function:
register_meta( string $object_type, string $meta_key, array $args, string|array $deprecated = null )
My questions are:
- [updated] How can I register the custom meta field for all of the post types in this list
[ 'post', 'page', 'attachement' ]
? - How can I still follow the same serialized way of saving the data in a single field if the types ($args->type) supported when registering a meta are only 'string', 'boolean', 'integer', and 'number'?
Right now if I just register the _custom_key
meta using:
register_meta( 'post', '_custom_key', [
'show_in_rest' => true,
'single' => true,
'type' => 'string',
'auth_callback' => function () {
return current_user_can( 'edit_posts' );
}
]);
I will get a Notice: Array to string conversion in .../wp-includes/rest-api/fields/class-wp-rest-meta-fields.php
because already saved data from the DB is serialized.
and typing in the console: wp.data.select( 'core/editor' ).getCurrentPost().meta;
will return a string: {_custom_key: "Array"}
.
register_meta()
does not support array values), but in regards to 1,object_type
is not the same aspost_type
. The object type refers to whether it's for a post type, user or term. If you want to register it for specific post types, setobject_type
topost
andobject_subtype
(in the args array) to the post type.object_subtype
still accepts only a string. Does that mean that I have to register the meta for each post I want?