如何为WordPress自定义菜单页添加可关闭的admin_notices
先拆解你的两个核心问题:一是用admin_notices钩子的通知全站显示,二是自定义菜单页里的通知关闭按钮没反应。咱们逐个给出解决方案:
1. 限制Admin Notice仅在自定义菜单页显示
admin_notices钩子默认会在所有后台页面触发,所以要加个页面判断逻辑。用WordPress内置的get_current_screen()函数获取当前后台页面的标识,对比你的自定义菜单页的menu_slug,只有匹配时才输出通知。
修改你的钩子代码:
function display_admin_notice() { // 获取当前后台屏幕对象 $current_screen = get_current_screen(); // 替换成你注册自定义菜单时用的menu_slug $target_menu_slug = 'your-custom-menu-slug'; // 仅在目标自定义页面显示通知 if ( $current_screen && $current_screen->id === $target_menu_slug ) { ?> <div class="notice notice-success is-dismissible"> <p>The secret to success is to know something nobody else knows ~ Aristotle Onassis</p> </div> <?php } } add_action( 'admin_notices', 'display_admin_notice' );
这里的your-custom-menu-slug需要替换成你调用add_menu_page()或add_submenu_page()时传入的菜单标识参数。
2. 修复自定义菜单页关闭按钮失效的问题
自定义菜单页默认不会自动加载WordPress处理notice-dismiss的核心JS脚本,导致点击关闭按钮没有响应。有两种靠谱的解决方式:
方法一:加载WordPress官方的通知处理脚本
在自定义菜单页的脚本加载钩子中,注册并加载common脚本(这个脚本包含了通知关闭的核心逻辑):
function enqueue_custom_menu_scripts( $hook_suffix ) { // 替换成你的自定义菜单页的hook后缀,格式参考:顶级菜单是`toplevel_page_{menu_slug}`,子菜单是`{父菜单slug}_page_{子菜单slug}` $target_hook = 'toplevel_page_your-custom-menu-slug'; if ( $hook_suffix === $target_hook ) { // 加载WordPress核心的common脚本,包含通知关闭逻辑 wp_enqueue_script( 'common' ); } } add_action( 'admin_enqueue_scripts', 'enqueue_custom_menu_scripts' );
不确定$target_hook的话,可以在自定义菜单页里临时加var_dump($hook_suffix)打印出正确的钩子后缀。
方法二:手动绑定关闭事件
如果不想加载额外的核心脚本,也可以自己写简单的JS来处理关闭逻辑:
function add_custom_notice_dismiss_script() { $current_screen = get_current_screen(); $target_menu_slug = 'your-custom-menu-slug'; if ( $current_screen && $current_screen->id === $target_menu_slug ) { ?> <script> document.addEventListener('DOMContentLoaded', function() { const dismissButtons = document.querySelectorAll('.notice-dismiss'); dismissButtons.forEach(button => { button.addEventListener('click', function(e) { e.preventDefault(); // 隐藏当前通知 this.closest('.notice').style.display = 'none'; // 如果需要持久化关闭(比如用户关闭后下次不再显示),可以在这里添加cookie或用户元数据的逻辑 }); }); }); </script> <?php } } add_action( 'admin_footer', 'add_custom_notice_dismiss_script' );
这个方法直接给关闭按钮绑定点击事件,点击后隐藏通知,简单直接。如果需要实现“关闭后不再显示”的效果,还可以扩展添加cookie存储或用户数据库字段的逻辑。
为什么大型插件能正常工作?
那些成熟插件要么在自定义页面正确加载了WordPress的核心脚本,要么自己实现了完整的通知关闭逻辑,同时也做了严格的页面范围判断,所以能实现正常显示和关闭的效果。
内容的提问来源于stack exchange,提问作者jayantsoni002

