How to update a meta field of type array in Gutenberg
In a plugin I'm building for Gutenberg, I register a meta field named _related_posts
, which stores an array of post ids:
PHP:
function register_meta_fields() {
register_post_meta( '', '_related_posts', array(
'show_in_rest' = true,
'single' = true,
'type' = 'array',
'show_in_rest' = array(
'schema' = array(
'type' = 'array',
'items' = array(
'type' = 'integer',
),
),
),
'auth_callback' = function() {
return current_user_can( 'edit_posts' );
}
) );
}
I'm using the useEntityProp
hook to get and set this meta field in JS:
JS:
const [ meta, setMeta ] = useEntityProp(
'postType',
'post',
'meta'
);
I have a onUpdateRelatedPosts()
function that gets called when the user selects a post from a list:
JS:
function onUpdateRelatedPosts( post ) {
setMeta( { ...meta, '_related_posts': [post.id] } );
}
This function takes a post object as an argument and stores its id in the _related_posts
meta field, but I can't get it to work as I want. It doesn't append the id at the end of the array but replaces the whole meta field with the added id.
What am I doing wrong?
Topic block-editor hooks custom-field Wordpress javascript
Category Web