钩子文档

admin_notices

💡 云策文档标注

概述

admin_notices 是 WordPress 中用于在管理后台显示通知消息的 Hook。开发者可以通过添加动作到 admin_notices 来输出自定义通知,支持多种样式和交互选项。

关键要点

  • 使用 admin_notices Hook 来触发通知显示,通过 add_action 绑定自定义函数。
  • 通知通过输出带有特定 CSS 类的 div 元素实现,核心类为 notice,并配合 notice-error、notice-warning、notice-success、notice-info 等子类定义样式。
  • 可添加 is-dismissible 类使通知可关闭,但关闭状态仅限当前页面,页面刷新后通知会重新出现。
  • 避免使用 update-nag 类,因为它会导致样式和布局异常,不适合常规插件或主题通知。
  • 通知内容应包裹在 p 标签内以确保正确内边距。
  • WordPress 6.4 引入了新函数 wp_admin_notice() 和 wp_get_admin_notice() 来简化通知输出。
  • 对于 Block Editor 屏幕,admin_notices Hook 可能无效,需额外使用 JavaScript 输出通知。
  • 可使用第三方包(如 WPTRT/admin-notices)或自定义类(如 Log_Warning)来标准化和动态管理通知。
  • 注意 DISABLE_NAG_NOTICES 常量可用于自愿禁用某些“nag”通知,但支持有限。

代码示例

function sample_admin_notice__error() {
    $class = 'notice notice-error';
    $message = __( 'Irks! An error has occurred.', 'sample-text-domain' );
    printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( $message ) );
}
add_action( 'admin_notices', 'sample_admin_notice__error' );

注意事项

  • 通知样式基于 CSS 类,确保正确使用 notice 和子类以避免布局问题。
  • is-dismissible 仅提供前端交互,不持久化关闭状态,需后端逻辑处理持久关闭。
  • 在插件或主题中输出通知时,考虑使用可翻译字符串和转义函数(如 esc_html)以增强安全性。
  • 对于复杂通知需求,推荐使用官方或社区提供的标准化解决方案。

📄 原文内容

Prints admin screen notices.

More Information

Example

In order to display a notice, echo a div with the class notice and one of the following classes:

* notice-error – will display the message with a white background and a red left border.
* notice-warning– will display the message with a white background and a yellow/orange left border.
* notice-success – will display the message with a white background and a green left border.
* notice-info – will display the message with a white background a blue left border.
* optionally use is-dismissible to add a closing icon to your message via JavaScript. Its behavior, however, applies only on the current screen. It will not prevent a message from re-appearing once the page re-loads, or another page is loaded.

Don’t use update-nag as a class name!
It is not suitable for regular admin notices, as it will apply different layout styling to the message. Additionally it will trigger the message to be moved above the page title (<h1>), thus semantically prioritizing it above other notices which is not likely to be appropriate in a plugin or theme context.

The inner content of the div is the message, and it’s a good idea to wrap the message in a paragraph tag <p> for the correct amount of padding in the output.

function sample_admin_notice__success() {
?>
<div class="notice notice-success is-dismissible">
<p></p>
</div>
</pre>


<pre class="wp-block-code"><code lang="php" class="language-php line-numbers">function sample_admin_notice__error() {
$class = 'notice notice-error';
$message = __( 'Irks! An error has occurred.', 'sample-text-domain' );

printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( $message ) );
}
add_action( 'admin_notices', 'sample_admin_notice__error' );

Source

do_action( 'admin_notices' );

Changelog

Version Description
3.1.0 Introduced.

User Contributed Notes

  1. Skip to note 11 content

    Sample Usage

    function sample_admin_notice__success() {
        ?>
        <div class="notice notice-success is-dismissible">
            <p></p>
        </div>
        </pre>
    <p>The class <code>notice-success</code> will display the message with a white background and a green left border.</p>
    <pre class="wp-block-code"><code lang="php" class="language-php line-numbers">function sample_admin_notice__error() {
    	$class = 'notice notice-error';
    	$message = __( 'Irks! An error has occurred.', 'sample-text-domain' );
    
    	printf( '<div class="%1$s"><p>%2$s</p></div>', esc_attr( $class ), esc_html( $message ) ); 
    }
    add_action( 'admin_notices', 'sample_admin_notice__error' );

    The class notice-error will display the message with a white background and a red left border.

    Use notice-warning for a yellow/orange, and notice-info for a blue left border.

    The class name is-dismissible will automatically trigger a closing icon to be added to your message via JavaScript. Its behavior, however, applies only on the current screen. It will not prevent a message from re-appearing once the page re-loads, or another page is loaded.

    [copied/pasted from https://codex.wordpress.org/Plugin_API/Action_Reference/admin_notices%5D

  2. Skip to note 12 content

    Method to display message dynamically (Taking example of warning message)

    /**
     * Class to log warnings.
     */
    class Log_Warning {
    	/**
    	 * Message to be displayed in a warning.
    	 *
    	 * @var string
    	 */
    	private string $message;
    
    	/**
    	 * Initialize class.
    	 *
    	 * @param string $message Message to be displayed in a warning.
    	 */
    	public function __construct( string $message ) {
    		$this->message = $message;
    
    		add_action( 'admin_notices', array( $this, 'render' ) );
    	}
    
    	/**
    	 * Displays warning on the admin screen.
    	 *
    	 * @return void
    	 */
    	public function render() {
    		printf( '<div class="notice notice-warning is-dismissible"><p>Warning: %s</p></div>', esc_html( $this->message ) );
    	}
    }

    Now you can simply initialize the class to display a dynamic message.

    new Log_Warning( 'Image should contain async tag' );

  3. Skip to note 13 content

    As of WordPress 6.4, you can output admin notice/messages with two new functions (which are yet to be documented):

    wp_admin_notice() and wp_get_admin_notice();

    First parameter is your message as a string; second parameter is an args array with the most useful being type: [ 'type' => 'error' ].

    So for example:

    if ( $error === true ) {
      wp_admin_notice( 'There was an error!', [ 'type' => 'error' ] );
    }

    More information:
    https://make.wordpress.org/core/2023/10/16/introducing-admin-notice-functions-in-wordpress-6-4/

  4. Skip to note 14 content

    The Theme Review Team (TRT) released a package you can use in your theme or plugin to create admin notices:
    https://github.com/WPTRT/admin-notices

    Its primary purpose is for providing a standardized method of creating admin notices in a consistent manner using the default WordPress styles.

    Notices created using this method are automatically dismissible.

  5. Skip to note 15 content

    Information on the unofficial, voluntary flag 'DISABLE_NAG_NOTICES' is missing. Here are relevant details from the old codex page:

    Disable Nag Notices
    In late 2017, an unofficial defined constant was proposed by LittleBizzy as a voluntary way for plugin or theme authors to allow for hiding certain admin notices that may be considered bothersome by some webmasters. It can be used as follows:

    define('DISABLE_NAG_NOTICES', true);

    It should be noted that there is no universal support for this constant, although a limited number of plugin and theme authors have begun to support it. A typical use case might be for hiding recurring “nag” notices that ask users to review their extension on WordPress.org, etc. Furthermore, it should not have any effect on general notices that appear within WP Admin, and is simply a way for extensions to opt in to disabling certain notices at their own discretion.

    Usage sample:

    if ( ! defined( 'DISABLE_NAG_NOTICES' ) || ! DISABLE_NAG_NOTICES ) {
    	add_action( 'admin_notices', 'my_admin_notice_renderer' );
    }

  6. Skip to note 16 content

    In order to display a notice, echo a div with the class notice and one of the following classes:

    * notice-error – will display the message with a red left border.
    * notice-warning– will display the message with a yellow/orange left border.
    * notice-success – will display the message with a green left border.
    * notice-info – will display the message with a blue left border.
    * optionally use is-dismissible to add a closing icon to your message via JavaScript. Its behavior, however, applies only on the current screen. It will not prevent a message from re-appearing once the page re-loads, or another page is loaded.

    Don’t use update-nag as a class name! It is not suitable for regular admin notices, as it will apply different layout styling to the message. Additionally it will trigger the message to be moved above the page title, thus semantically prioritizing it above other notices which is not likely to be appropriate in a plugin or theme context.

    The inner content of the div is the message, and it’s a good idea to wrap the message in a paragraph tag for the correct amount of padding in the output.

  7. Skip to note 17 content

    Here’s a simple way to add an independence day notice to some admin pages.

    add_action( 'admin_notices', 'independence_notice' );
    
    function independence_notice() {
        global $pagenow;
    	$admin_pages = [ 'index.php', 'edit.php', 'plugins.php' ];
        if ( in_array( $pagenow, $admin_pages ) ) {
    		if ( date( 'j, F' ) === '1, October' ) { 
    			?>
    			<div class="notice notice-warning is-dismissible">
    				<p>Happy Independence Day, Nigeria...</p>
    			</div>
    			</pre>
    				</div><!-- .comment-content -->
    
    					<section id='feedback-5370' class='wporg-has-embedded-code feedback hide-if-js' data-comment-count='0'>
    </section><!-- .feedback -->
    <footer class='feedback-links wporg-dot-link-list' >
    <a role="button" class="feedback-login" href="https://login.wordpress.org/?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Fhooks%2Fadmin_notices%2F%3Freplytocom%3D5370%23feedback-editor-5370" rel="nofollow">Log in to add feedback</a></footer>
    </article><!-- .comment-body -->
    </li>
    			<li id="comment-3462" data-comment-id="3462" class="comment byuser comment-author-mamesweb odd alt thread-odd thread-alt depth-1">
    			<article id="div-comment-3462" class="comment-body">
    
    							<a href="#comment-content-3462" class="screen-reader-text">Skip to note 18 content</a>
    				<header class="comment-meta">
    					<div class="comment-author vcard">
    						<span class="comment-author-attribution">
    						<a href="https://profiles.wordpress.org/mamesweb/" rel="external nofollow" class="url">Munir Mahmud</a>						</span>
    						<a class="comment-date" href="https://developer.wordpress.org/reference/hooks/admin_notices/#comment-3462">
    							<time datetime="2019-11-09T10:53:58+00:00">
    							6 years ago							</time>
    						</a>
    
    																													</div>
    					<div class="user-note-voting" data-nonce="09923aae2e" data-can-vote="false"><a class="user-note-voting-up" title="You must log in to vote on the helpfulness of this note" data-id="3462" data-vote="up" href="https://login.wordpress.org?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Fhooks%2Fadmin_notices%2F%23comment-3462"><span class="screen-reader-text">You must log in to vote on the helpfulness of this note</span></a><span class="user-note-voting-count " title="50% like this"><span class="screen-reader-text">Vote results for this note: </span>0</span><a class="user-note-voting-down" title="You must log in to vote on the helpfulness of this note" data-id="3462" data-vote="down" href="https://login.wordpress.org?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Fhooks%2Fadmin_notices%2F%23comment-3462"><span class="screen-reader-text">You must log in to vote on the helpfulness of this note</span></a></div>				</header>
    				<!-- .comment-metadata -->
    			
    				<div class="wporg-has-embedded-code comment-content" id="comment-content-3462">
    				<pre class="wp-block-code"><code lang="php" class="language-php line-numbers">//Display admin notices 
    function my_test_plugin_admin_notice()
    {
    	//get the current screen
    	$screen = get_current_screen();
    
    	//return if not plugin settings page 
    	//To get the exact your screen ID just do var_dump($screen)
    	if ( $screen->id !== 'toplevel_page_YOUR_PLUGIN_PAGE_SLUG') return;
    		
    	//Checks if settings updated 
    	if ( isset( $_GET['settings-updated'] ) ) {
    		//if settings updated successfully 
    		if ( 'true' === $_GET['settings-updated'] ) : ?>
    
    			<div class="notice notice-success is-dismissible">
    				<p></p>
    			</div>
    
    		
    
    			<div class="notice notice-warning is-dismissible">
    				<p></p>
    			</div>
    			
    		</pre>
    <p>The class notice-success will display the message with a white background and a green left border and the class notice-error will display the message with a white background and a red left border. </p>
    <p>if you want to display the errors you can also use notice-warning for a yellow/orange for a blue left border.</p>
    				</div><!-- .comment-content -->
    
    					<section id='feedback-3462' class='wporg-has-embedded-code feedback hide-if-js' data-comment-count='0'>
    </section><!-- .feedback -->
    <footer class='feedback-links wporg-dot-link-list' >
    <a role="button" class="feedback-login" href="https://login.wordpress.org/?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Fhooks%2Fadmin_notices%2F%3Freplytocom%3D3462%23feedback-editor-3462" rel="nofollow">Log in to add feedback</a></footer>
    </article><!-- .comment-body -->
    </li>
    			<li id="comment-6325" data-comment-id="6325" class="comment byuser comment-author-pkostadinov even thread-even depth-1">
    			<article id="div-comment-6325" class="comment-body">
    
    							<a href="#comment-content-6325" class="screen-reader-text">Skip to note 19 content</a>
    				<header class="comment-meta">
    					<div class="comment-author vcard">
    						<span class="comment-author-attribution">
    						<a href="https://profiles.wordpress.org/pkostadinov/" rel="external nofollow" class="url">pkostadinov</a>						</span>
    						<a class="comment-date" href="https://developer.wordpress.org/reference/hooks/admin_notices/#comment-6325">
    							<time datetime="2023-02-02T18:42:13+00:00">
    							3 years ago							</time>
    						</a>
    
    																													</div>
    					<div class="user-note-voting" data-nonce="8503973d4c" data-can-vote="false"><a class="user-note-voting-up" title="You must log in to vote on the helpfulness of this note" data-id="6325" data-vote="up" href="https://login.wordpress.org?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Fhooks%2Fadmin_notices%2F%23comment-6325"><span class="screen-reader-text">You must log in to vote on the helpfulness of this note</span></a><span class="user-note-voting-count " title=""><span class="screen-reader-text">Vote results for this note: </span>0</span><a class="user-note-voting-down" title="You must log in to vote on the helpfulness of this note" data-id="6325" data-vote="down" href="https://login.wordpress.org?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Fhooks%2Fadmin_notices%2F%23comment-6325"><span class="screen-reader-text">You must log in to vote on the helpfulness of this note</span></a></div>				</header>
    				<!-- .comment-metadata -->
    			
    				<div class="wporg-has-embedded-code comment-content" id="comment-content-6325">
    				<p>The <code>admin_notices</code> hook doesn’t do anything on a Block Editor screen. For that reason you need to print it second time with JS.</p>
    <p>Here is an example, of how to make a notification that will show on Post Edit Screen if Gutenberg is used:</p>
    <pre class="wp-block-code"><code lang="php" class="language-php line-numbers">add_action( 'admin_notices', 'wpdocs_custom_notice' );
    
    function wpdocs_custom_notice(): void {
    	$message = 'Hello World!';
    	$type    = 'info';
    
    	if ( empty( $message ) || empty( $type ) ) {
    		return;
    	}
    
    	?>
    	<div class="notice notice-<?php echo esc_attr( $type ); ?> is-dismissible">
    		
    	</div>
    
    	<script>
    		( function( wp ) {
    			wp.data.dispatch( 'core/notices' ).createNotice(
    				'<?php echo sanitize_text_field( $type ); ?>',
    				'<?php echo sanitize_text_field( $message ); ?>',
    				{
    					isDismissible: true,
    				}
    			);
    		} )( window.wp );
    	</script>
    	</pre>
    				</div><!-- .comment-content -->
    
    					<section id='feedback-6325' class='wporg-has-embedded-code feedback hide-if-js' data-comment-count='0'>
    </section><!-- .feedback -->
    <footer class='feedback-links wporg-dot-link-list' >
    <a role="button" class="feedback-login" href="https://login.wordpress.org/?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Fhooks%2Fadmin_notices%2F%3Freplytocom%3D6325%23feedback-editor-6325" rel="nofollow">Log in to add feedback</a></footer>
    </article><!-- .comment-body -->
    </li>
    			<li id="comment-6396" data-comment-id="6396" class="comment byuser comment-author-jorensm odd alt thread-odd thread-alt depth-1">
    			<article id="div-comment-6396" class="comment-body">
    
    							<a href="#comment-content-6396" class="screen-reader-text">Skip to note 20 content</a>
    				<header class="comment-meta">
    					<div class="comment-author vcard">
    						<span class="comment-author-attribution">
    						<a href="https://profiles.wordpress.org/jorensm/" rel="external nofollow" class="url">jorensm</a>						</span>
    						<a class="comment-date" href="https://developer.wordpress.org/reference/hooks/admin_notices/#comment-6396">
    							<time datetime="2023-03-10T09:59:02+00:00">
    							3 years ago							</time>
    						</a>
    
    																													</div>
    					<div class="user-note-voting" data-nonce="06ef477992" data-can-vote="false"><a class="user-note-voting-up" title="You must log in to vote on the helpfulness of this note" data-id="6396" data-vote="up" href="https://login.wordpress.org?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Fhooks%2Fadmin_notices%2F%23comment-6396"><span class="screen-reader-text">You must log in to vote on the helpfulness of this note</span></a><span class="user-note-voting-count " title=""><span class="screen-reader-text">Vote results for this note: </span>0</span><a class="user-note-voting-down" title="You must log in to vote on the helpfulness of this note" data-id="6396" data-vote="down" href="https://login.wordpress.org?redirect_to=https%3A%2F%2Fdeveloper.wordpress.org%2Freference%2Fhooks%2Fadmin_notices%2F%23comment-6396"><span class="screen-reader-text">You must log in to vote on the helpfulness of this note</span></a></div>				</header>
    				<!-- .comment-metadata -->
    			
    				<div class="wporg-has-embedded-code comment-content" id="comment-content-6396">
    				<p>Here is code to display a notice after a page refresh(for example after a post has been saved/updated). </p>
    <pre class="wp-block-code"><code lang="php" class="language-php line-numbers">class WPDocsAdminNotice {
    	const NOTICE_FIELD = 'wpdocs_admin_notice_message';
    
    	public function displayAdminNotice() {
    		$option      = get_option( self::NOTICE_FIELD );
    		$message     = isset( $option['message'] ) ? $option['message'] : false;
    		$noticeLevel = ! empty( $option['notice-level'] ) ? $option['notice-level'] : 'notice-error';
    
    		if ( $message ) {
    			echo $message;
    			delete_option( self::NOTICE_FIELD );
    		}
    	}
    
    	public static function displayError( $message ) {
    		self::updateOption($message, 'notice-error');
    	}
    
    	public static function displayWarning( $message ) {
    		self::updateOption($message, 'notice-warning');
    	}
    
    	public static function displayInfo( $message ) {
    		self::updateOption($message, 'notice-info');
    	}
    
    	public static function displaySuccess( $message ) {
    		self::updateOption($message, 'notice-success');
    	}
    
    	protected static function updateOption( $message, $noticeLevel ) {
    		update_option( self::NOTICE_FIELD, array(
    			'message' => $message,
    			'notice-level' => $noticeLevel
    		) );
    	}
    }

    Usage

    Add this action at the top level of your code:

    add_action( 'admin_notices', array( new WPDocsAdminNotice(), 'displayAdminNotice' ) );

    Then use the class anywhere in your code:

    WPDocsAdminNotice::displayError( __( 'An error occurred, check logs.' ) );