2

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:"hello@me.me";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:

  1. [updated] How can I register the custom meta field for all of the post types in this list [ 'post', 'page', 'attachement' ]?
  2. 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"}.

  • 1
    I don't know the answer to 2 (as far as I can tell, register_meta() does not support array values), but in regards to 1, object_type is not the same as post_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, set object_type to post and object_subtype (in the args array) to the post type. – Jacob Peattie Mar 6 at 13:39
  • object_subtype still accepts only a string. Does that mean that I have to register the meta for each post I want? – Vlad Mar 6 at 14:50
  • Seems that way. – Jacob Peattie Mar 6 at 14:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.