函数文档

wp_admin_notice()

💡 云策文档标注

概述

wp_admin_notice() 是 WordPress 6.4.0 引入的函数,用于在管理后台输出通知消息。它接受消息字符串和参数数组,支持自定义通知类型、可关闭性等属性。

关键要点

  • 函数 wp_admin_notice( $message, $args = array() ) 输出管理通知,参数 $message 为必需的消息字符串,$args 为可选参数数组。
  • $args 参数包括 type(如 'error'、'success')、dismissible(是否可关闭)、id(ID 属性)、additional_classes(额外 CSS 类)、attributes(额外属性)和 paragraph_wrap(是否用段落标签包裹消息)。
  • 函数内部触发 wp_admin_notice 动作钩子,并调用 wp_get_admin_notice() 生成标记,使用 wp_kses_post() 进行安全过滤。
  • 在插件中使用时,建议通过 add_action( 'admin_notices', ... ) 钩子调用 wp_admin_notice(),以避免直接输出错误。

代码示例

add_action( 'admin_notices', function () {
    wp_admin_notice(
        __( 'Your success message here.', 'your-text-domain' ),
        array(
            'id'                 => 'message',
            'additional_classes' => array( 'updated' ),
            'dismissible'        => true,
        )
    );
} );

注意事项

wp_admin_notice() 自 WordPress 6.4.0 版本引入,使用时需确保 WordPress 版本兼容。相关函数包括 wp_get_admin_notice()、wp_kses_post() 和 do_action()。


📄 原文内容

Outputs an admin notice.

Parameters

$messagestringrequired
The message to output.
$argsarrayoptional
An array of arguments for the admin notice.

  • type string
    Optional. The type of admin notice.
    For example, 'error', 'success', 'warning', 'info'.
  • dismissible bool
    Optional. Whether the admin notice is dismissible. Default false.
  • id string
    Optional. The value of the admin notice’s ID attribute.
  • additional_classes string[]
    Optional. A string array of class names.
  • attributes string[]
    Optional. Additional attributes for the notice div.
  • paragraph_wrap bool
    Optional. Whether to wrap the message in paragraph tags. Default true.

Default:array()

Source

function wp_admin_notice( $message, $args = array() ) {
	/**
	 * Fires before an admin notice is output.
	 *
	 * @since 6.4.0
	 *
	 * @param string $message The message for the admin notice.
	 * @param array  $args    The arguments for the admin notice.
	 */
	do_action( 'wp_admin_notice', $message, $args );

	echo wp_kses_post( wp_get_admin_notice( $message, $args ) );
}

Hooks

do_action( ‘wp_admin_notice’, string $message, array $args )

Fires before an admin notice is output.

Changelog

Version Description
6.4.0 Introduced.

User Contributed Notes

  1. Skip to note 3 content

    In the plugin php file, using wp_admin_notice() throws an error, I just wrap it in the add_action hook

    add_action( 'admin_notices', function () {
    	wp_admin_notice(
    		__( 'Your success message here.', 'your-text-domain' ),
    		array(
    			'id'                 => 'message',
    			'additional_classes' => array( 'updated' ),
    			'dismissible'        => true,
    		)
    	);
    } );