There can be instances where you might want to prevent publishing a post until certain conditions are met. Although you can handle this in PHP using action hooks, Gutenberg provides an action called lockPostSaving that disables any attempt to save a post.
Let’s set a silly goal for the sake of learning:
Goal: Create a Gutenberg plugin that doesn’t allow the post author to save/publish a post if the post title is empty.
Our goal is pretty simple, so let’s get started!
Register the plugin
import { registerPlugin } from "@wordpress/plugins";
function TitleChecker() {
return null;
}
registerPlugin( 'empty-title-check', {
render: TitleChecker
} );
Code language: JavaScript (javascript)
We have registered a plugin called empty-title-check
, which accepts a component called <TitleChecker />
We return null
because we don’t need to render anything.
Get the post title
import { registerPlugin } from "@wordpress/plugins";
import { useSelect } from "@wordpress/data";
function TitleChecker() {
const { postTitle } = useSelect( select => {
const { getEditedPostAttribute } = select( 'core/editor' );
return {
postTitle: getEditedPostAttribute( 'title' ),
}
} );
console.log( postTitle )
return null;
}
registerPlugin( 'empty-title-check', {
render: TitleChecker
} );
Code language: TypeScript (typescript)
The post title data is part of the core/editor
data store. Open your developer console and update the post title. You will notice that it logs the updated post title. So far, so good.
import { registerPlugin } from "@wordpress/plugins";
import { useSelect, useDispatch } from "@wordpress/data";
function TitleChecker() {
const { postTitle } = useSelect( select => {
const { getEditedPostAttribute } = select( 'core/editor' );
return {
postTitle: getEditedPostAttribute( 'title' ),
}
} );
/**
* Methods to lock and unlock post saving.
*/
const { lockPostSaving, unlockPostSaving } = useDispatch( 'core/editor' );
/**
* If post title is empty, then lock post saving,
* else release lock.
*/
if ( ! postTitle.length ) {
lockPostSaving( 'title-empty-lock' );
} else {
unlockPostSaving( 'title-empty-lock' );
}
return null;
}
registerPlugin( 'empty-title-check', {
render: TitleChecker
} );
Code language: TypeScript (typescript)
Lock post saving if title is empty
If the post title is empty, we run lockPostSaving
and give it an ID title-empty-lock
. When the post title is not empty, we call another action called unlockPostSaving
and refer to the same ID: title-empty-lock
to release the lock.
Leave a Reply