Conditionally prevent publishing/updating in Gutenberg

It is possible to disable the publish/update button in Gutenberg. With that, we could, for example, force the user to add data to a custom block that adds metadata to a custom post type.

lockPostSaving and unlockPostSaving

The functions lockPostSaving() and unlockPostSaving() from the data module allow to lock and unlock the publish/update possibility in Gutenberg. The functions get a name as the parameter to be able to lock a post or page with multiple conditions. Until one lock is not unlocked, the post cannot be published or updated.

In practice, locking the button looks like that:

wp.data.dispatch( 'core/editor' ).lockPostSaving( 'requiredValueLock' );
Code language: PHP (php)

And unlocking it again like that:

wp.data.dispatch( 'core/editor' ).unlockPostSaving( 'requiredValueLock' );
Code language: PHP (php)

In conjunction with the subscribe() function from the data module, which fires when something in the editor changes, we can monitor a condition and lock/unlock the content depending on if the condition is met or not.

Here is an example that locks the button when the meta key required_value is empty:

const { subscribe, select, dispatch, } = wp.data; wp.domReady( () => { const postType = select( 'core/editor' ).getCurrentPostType(); if ( postType === 'portfolio' ) { let locked = false; // Subscribe to editor state changes. let checkRequiredField = subscribe( () => { // Get meta values of post. const meta = select( 'core/editor' ).getEditedPostAttribute( 'meta' ); if ( meta.required_value !== undefined && meta.required_value === '' ) { // Lock post, if not already locked. if ( ! locked ) { locked = true; dispatch( 'core/editor' ).lockPostSaving( 'requiredValueLock' ); } } else { // Unlock post if locked. if ( locked ) { locked = false; dispatch( 'core/editor' ).unlockPostSaving( 'requiredValueLock' ); } } } ); } } );
Code language: PHP (php)

First, we store subscribe, select, and dispatch from the data module in variables with the same name, to have less writing work later.

We use wp.domReady() to wait until the editor finished loading and check if the currently viewed content is of the portfolio post type. Only for those posts, we want to check the condition.

We hook us to editor changes with subscribe(), and the code inside its parameter function is called each time the editor changes. On a change, we get the meta values of the post. If a block changes a meta value, that value is returned instead of the one from the database.

Next, we check if meta.required_value exists (if there is a value for the meta key required_value), and if it is an empty string. If that is true, we lock the post if it is not already locked.

If the key does not exist or is not empty, we unlock the post again.

Leave a Reply

Your email address will not be published. Required fields are marked *