When you do this: '_related_posts': [post.id]
, you’re actually overriding the entire array or the meta value, so to instead append an item to the existing array, you can use the spread (...
) syntax like so: '_related_posts': [ ...meta._related_posts, post.id ]
.
But you may not want to update the meta if the selected post ID is already in the current meta value, i.e.
// Add the post (ID) if it's not already in the list.
if ( meta._related_posts.indexOf( post.id ) < 0 ) {
setMeta( { ...meta, '_related_posts': [ ...meta._related_posts, post.id ] } );
}
That’s just a suggestion (to avoid duplicate values), though.
And BTW, for property names that do not contain characters that are not alphanumeric or underscore (_
), it’s not mandatory to enclose the property name in quotes. So for example in your case, _related_posts:
(as opposed to having the quotes: '_related_posts':
) would be fine. 🙂