You can display four types of notices in the WordPress Block Editor (a.k.a. Gutenberg) using JavaScript: error, warning, info, and success. Here is an example of each.
WordPress Gutenberg Error
wp.data.dispatch('core/notices').createErrorNotice(
'There was an error',
{id: 'my-error'}
);
WordPress Gutenberg Warning
wp.data.dispatch('core/notices').createWarningNotice(
'You are warned',
{id: 'my-warn'}
);
WordPress Gutenberg Info
wp.data.dispatch('core/notices').createInfoNotice(
'You are informed',
{id: 'my-info'}
);
WordPress Gutenberg Success
wp.data.dispatch('core/notices').createSuccessNotice(
'Success',
{id: 'my-success'}
);
Why Include an id ?
You’ll notice in each example we include an id
as part of the object passed as the second parameter. When a notice is created WordPress checks if a notice already exists with that id
, if a notice does already exist, the new notice replaces the old notice.
This is useful when your code that creates the notice is called multiple times. Without the id
we’d get multiple copies of our notice when typically we just want one.
This code will display three notices.
wp.data.dispatch('core/notices').createWarningNotice(
'Be careful1!'
);
wp.data.dispatch('core/notices').createWarningNotice(
'Be careful2!'
);
wp.data.dispatch('core/notices').createWarningNotice(
'Be careful3!'
);
This code will display one notice.
Each notice in the following code will replace the one that came before it. Only one notice will ever be displayed.
wp.data.dispatch('core/notices').createWarningNotice(
'More be careful1!',
{id: 'salcode-warn'}
);
wp.data.dispatch('core/notices').createWarningNotice(
'More be careful2!',
{id: 'salcode-warn'}
);
wp.data.dispatch('core/notices').createWarningNotice(
'More be careful3!',
{id: 'salcode-warn'}
);
More Information about Creating Notices
See WordPress Block Editor Core Notices
Leave a Reply