简体   繁体   English

回声 <style'> WordPress中导致“无法修改标题信息”错误

[英]Echo '<style'> in WordPress causes “Cannot modify header information” error

I have this code: 我有以下代码:

add_action('admin_init', 'wpse74389_check_username');
function wpse74389_check_username(){
$user = wp_get_current_user();
if( current_user_can('admin')){
    echo '<style>
li#menu-settings .wp-submenu.wp-submenu-wrap li:last-child {
display: none!important;
}
li#menu-settings .wp-submenu.wp-submenu-wrap li:nth-child(2) {
 display: none!important;
}
</style>';
}
}

I receive an error: 我收到一个错误:

Cannot modify header information - headers already sent by 无法修改标头信息-标头已由发送

You should use the admin_head action to add the code to WP-Admin. 您应该使用admin_head操作将代码添加到WP-Admin。

For example, replace your code with this: 例如,用以下代码替换您的代码:

add_action('admin_head', 'wpse74389_check_username'); // <-- Modified

function wpse74389_check_username(){
    $user = wp_get_current_user();
    if( current_user_can('admin')){
        echo '<style>
        li#menu-settings .wp-submenu.wp-submenu-wrap li:last-child {
        display: none!important;
        }
        li#menu-settings .wp-submenu.wp-submenu-wrap li:nth-child(2) {
        display: none!important;
        }
        </style>';
    }
}

The admin_init fires too early in WordPress for you to directly echo code to screen. admin_init在WordPress中触发还为时过早,您无法直接将代码echo到屏幕上。 This is what causes the error message you're seeing. 这就是导致您看到的错误消息的原因。

Cannot modify header information - headers already sent by 无法修改标头信息-标头已由发送

This error often occurs if you attempt to print any text to screen (using echo or print or even having text before your opening <?php tag). 如果您尝试在屏幕上打印任何文本(使用echoprint或什至在打开<?php标签之前包含文本),通常会发生此错误。

There's lots of information in this question , which focus on causes of the error. 这个问题中很多信息,这些信息集中在错误的原因上。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM