如何在WordPress管理端前台显示指定样式toast提示 现有代码无效果无报错
WordPress admin_notices 不生效问题解决方案
核心原因
你当前使用的 admin_notices 是WordPress专属的后台钩子,仅会在后台管理界面触发,不会在站点前台加载执行,所以不会生效也不会抛出报错。
同时你写的代码是生成WordPress默认的常驻后台通知,不是你预期的自动消失的toast提示效果,需要额外添加配置。
对应解决方案
场景1:需要在后台显示自动消失的toast提示
修改你的代码如下:
function sample_admin_notice__error() { $class = 'notice notice-error is-dismissible'; $message = __( '哎呀!发生了一个错误。', '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' ); // 新增JS实现自动隐藏toast效果 function admin_toast_auto_hide_script() { ?> <script> setTimeout(function(){ document.querySelectorAll('.notice.is-dismissible').forEach(function(notice){ notice.style.opacity = '0'; notice.style.transition = 'opacity 0.5s ease'; setTimeout(function(){ notice.remove(); }, 500); }); }, 3000); // 3秒后自动隐藏,可自行调整时长 </script> <?php } add_action( 'admin_footer', 'admin_toast_auto_hide_script' );
如果还是不生效,按以下顺序排查:
- 确认代码放在当前激活主题的
functions.php文件,或者自定义插件的主文件中 - 清空后台缓存后刷新页面测试
- 切换到WordPress默认主题测试,排除当前主题移除了
admin_notices输出的问题
场景2:需要在站点前台显示toast提示
不能使用admin_notices钩子,改用前台钩子并自行添加toast样式,参考代码:
function front_end_toast_notice() { ?> <style> .toast-notice { position: fixed; top: 20px; right: 20px; padding: 12px 24px; background: #dc3232; color: #fff; border-radius: 4px; z-index: 99999; opacity: 0; transition: opacity 0.5s ease; } .toast-notice.show { opacity: 1; } </style> <div class="toast-notice" id="customToast">哎呀!发生了一个错误。</div> <script> document.addEventListener('DOMContentLoaded', function(){ const toast = document.getElementById('customToast'); toast.classList.add('show'); setTimeout(function(){ toast.classList.remove('show'); setTimeout(function(){ toast.remove(); }, 500); }, 3000); }); </script> <?php } add_action( 'wp_footer', 'front_end_toast_notice' );
内容的提问来源于stack exchange,提问作者divyraj
相关产品推荐
相关产品推荐

