Skip to content

Admin notices

The AdminNotices service is used to display admin notices in the WordPress admin area.

Admin notices are used to communicate important information to the user, such as success messages, error messages, or warnings.

TIP

The service is automatically registered with the container and can be accessed by injecting it into your classes.

Displaying a notice

To display an admin notice, you can use the add() method of the AdminNotices service. The method accepts 4 parameters:

  1. The ID of the notice.
  2. The title of the notice.
  3. The message of the notice.
  4. An array of options for the notice.
php
$adminNotices->add('my_notice', 'My Notice', 'This is a notice message.', [
    'type' => 'success',
]);

Dismissing a notice

You can make a notice dismissible by adding the dismissible option to the notice options array. This will display a close button that allows the user to dismiss the notice.

php
$adminNotices->add('my_dismissible_notice', 'My Dismissible Notice', 'This is a dismissible notice message.', [
    'type' => 'info',
    'dismissible' => true,
]);

Notice types

The type option of the notice options array determines the appearance of the notice. The following types are available:

  • success: A success message.
  • error: An error message.
  • warning: A warning message.
  • info: An informational message.
php
$adminNotices->add('my_error_notice', 'My Error Notice', 'This is an error notice message.', [
    'type' => 'error',
]);

Available options

The following options are available for the notice options array:

  • type: The type of the notice.
  • dismissible: Whether the notice is dismissible.
  • scope: The scope of the notice. Can be global or user. Default is global.
  • alt_style: Whether to use an alternative style for the notice. Default is false.
  • capability: The capability required to dismiss the notice. Default is edit_theme_options.
  • option_prefix: The prefix for the option name. Default is metapress_notice_dismissed.
  • screen: An array of screens where the notice should be displayed. Default is [].

Reference documentation

Notices.php.