Adding Custom Notices for the Gutenberg Editor

Change is the only constant, and developers all know it. WordPress admin notices have changed and the good old PHP-based hooks no longer work for Gutenberg.

This blog post covers the easy way to add admin notices when a post gets added or updated, focusing mainly on the Gutenberg notices.

Gutenberg Notices

Let’s start with this working example and customize it to your needs.

Hook into save action.

Here we are using the publish_post action to add our callback after every time a post gets saved. Add a did_action check to make sure this callback executes on the first time and doesn’t repeat.

Other plugins or customizations may also use this action hook, so it is recommended to perform this did_action check.

Set the message on the callback.

Here is an example of a typical editorial workflow:

  • Author submits a blog post
  • Saved as Draft
  • Editor approves and publishes

The background action is sending email notifications to the author when the post gets published. Let your callback process the data and return the message you want to show in the notice. To keep this data easily accessible, we are using post meta.

Create a custom endpoint.

Register an endpoint using register_rest_route. We will be using the namespace and route during the AJAX call.

AJAX call

Now that we have an error message on meta, we have to fetch it via an AJAX request. To keep this simple, the admin script is added directly along with the PHP code. You can make it a separate file and enqueue it.

We need ‘subscribe’ and ‘select’ from WP data module.

const { subscribe,select } = wp.data;

Subscribe allows you to listen to changes in the state. By subscribing to isSavingPost(), you can call the AJAX request.

We are sending the post ID to the custom REST endpoint and displaying the message via createNotice.

Get the error and render it.

Now we have the error, custom endpoint, and the AJAX callback. Retrieve the message from post_meta and send it to the response.

Here is the plugin with the complete code in the repo. I hope you find this quick tip useful. Follow our blog for more WordPress tutorials.


Have a comment?

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

accessibilityadminaggregationanchorarrow-rightattach-iconbackupsblogbookmarksbuddypresscachingcalendarcaret-downcartunifiedcouponcrediblecredit-cardcustommigrationdesigndevecomfriendsgallerygoodgroupsgrowthhostingideasinternationalizationiphoneloyaltymailmaphealthmessagingArtboard 1migrationsmultiple-sourcesmultisitenewsnotificationsperformancephonepluginprofilesresearcharrowscalablescrapingsecuresecureseosharearrowarrowsourcestreamsupporttwitchunifiedupdatesvaultwebsitewordpress