Refresh a Metabox in the WordPress Block Editor

The WordPress block editor shows registered metaboxes under the post / page content, but since it does not reload the webpage when saving content, metaboxes are not refreshed or reloaded when you save a draft or publish the post / page.

If your metabox needs to be refreshed, to show the new saved content (like the WPSSO Core or JSM Show Post Metadata plugins, for example), you need to add a change listener in javascript and refresh your metabox (using an ajax call) after the block editor has finished saving the metaboxes.

You may have come across an example like this one:

const isSavingMetaBoxes = wp.data.select( 'core/edit-post' ).isSavingMetaBoxes;

var wasSaving = false;

wp.data.subscribe( function(){

    var isSaving = isSavingMetaBoxes();

    if ( wasSaving && ! isSaving ) {

        // Call your metabox refresh function here.
    }

    wasSaving = isSaving;
});

The logic in this example checks that the block editor is saving metaboxes, and if saving metaboxes is done (ie. was saving, but not saving anymore), then the metaboxes can be refreshed.

The problem with this example is that wasSaving must be stored outside of the function to save the earlier state, and this variable can be modified by other plugins (using the same variable name, for example). A better way is to create a “name space” for your function like this one (change “yourNameSpace” in this example to something unique):

const yourNameSpace = ( function(){

    const isSavingMetaBoxes = wp.data.select( 'core/edit-post' ).isSavingMetaBoxes;

    var wasSaving = false;

    return {

        refreshMetabox: function(){

            var isSaving = isSavingMetaBoxes();

            if ( wasSaving && ! isSaving ) {

                // Call your metabox refresh function here.
            }

            wasSaving = isSaving;
        },
    }
})();

wp.data.subscribe( yourNameSpace.refreshMetabox );
Find this content useful? Share it with your friends!