diff --git a/docs/reference-guides/data/data-core-edit-post.md b/docs/reference-guides/data/data-core-edit-post.md index e3fb22a1a7afe0..f91bc5ce6abc39 100644 --- a/docs/reference-guides/data/data-core-edit-post.md +++ b/docs/reference-guides/data/data-core-edit-post.md @@ -438,6 +438,10 @@ _Returns_ Update a metabox. +_Parameters_ + +- _originalPost_ `Object[]`: Values of the original post without modifications. + ### setAvailableMetaBoxesPerLocation Stores info about which Meta boxes are available in which location. diff --git a/packages/edit-post/src/store/actions.js b/packages/edit-post/src/store/actions.js index d00f7472382f80..e4636a29ea233c 100644 --- a/packages/edit-post/src/store/actions.js +++ b/packages/edit-post/src/store/actions.js @@ -277,9 +277,11 @@ export function setAvailableMetaBoxesPerLocation( metaBoxesPerLocation ) { /** * Update a metabox. + * + * @param {Object[]} originalPost Values of the original post without modifications. */ export const requestMetaBoxUpdates = - () => + ( originalPost ) => async ( { registry, select, dispatch } ) => { dispatch( { type: 'REQUEST_META_BOX_UPDATES', @@ -335,6 +337,32 @@ export const requestMetaBoxUpdates = formData.append( key, value ) ); + // Get the list of custom fields that have been modified in the store. + const modifiedFields = []; + Object.entries( post.meta ).forEach( ( [ key, value ] ) => { + if ( value !== originalPost?.meta[ key ] ) { + modifiedFields.push( key ); + } + } ); + + /* + * Override the fields included in metaboxes with the values modified in the store. + * + * Meta fields used in meta box include two properties in the request form: + * + * meta[1234][key]: my_custom_field + * meta[1234][value]: Custom field value + */ + for ( const [ formKey, metaFieldKey ] of formData.entries() ) { + if ( modifiedFields.includes( metaFieldKey ) ) { + formData.set( + // Override the value, not the key. + formKey.replace( '[key]', '[value]' ), + post.meta[ metaFieldKey ] + ); + } + } + try { // Save the metaboxes. await apiFetch( { @@ -470,7 +498,9 @@ export const initializeMetaBoxes = if ( metaBoxesInitialized ) { return; } - const postType = registry.select( editorStore ).getCurrentPostType(); + const { id: postId, type: postType } = registry + .select( editorStore ) + .getCurrentPost(); if ( window.postboxes.page !== postType ) { window.postboxes.add_postbox_toggles( postType ); } @@ -478,6 +508,9 @@ export const initializeMetaBoxes = metaBoxesInitialized = true; // Save metaboxes on save completion, except for autosaves. + const originalPost = registry + .select( coreStore ) + .getEntityRecord( 'postType', postType, postId ); addFilter( 'editor.__unstableSavePost', 'core/edit-post/save-metaboxes', @@ -491,7 +524,7 @@ export const initializeMetaBoxes = return; } - return dispatch.requestMetaBoxUpdates(); + return dispatch.requestMetaBoxUpdates( originalPost ); } ) );