无法修改标头信息 - 标头已经被发送... WordPress问题

44

我遇到了这个错误,但我不知道应该怎么处理。

无法修改头信息 - 头已经在 /home/ben213/public_html/wp-content/themes/Bendaggers/functions.php 的第9行开始输出, 在 /home/ben213/public_html/wp-includes/pluggable.php 的第934行发生错误。

我的Functions.php文件的第9行是:

<?php if(function_exists('register_sidebar'))register_sidebar();?>

我的pluggable.php # 934出了问题

function wp_redirect($location, $status = 302) {
    global $is_IIS;

    $location = apply_filters('wp_redirect', $location, $status);
    $status = apply_filters('wp_redirect_status', $status, $location);

    if ( !$location ) // allows the wp_redirect filter to cancel a redirect
        return false;

    $location = wp_sanitize_redirect($location);

    if ( !$is_IIS && php_sapi_name() != 'cgi-fcgi' )
        status_header($status); // This causes problems on IIS and some FastCGI setups

    header("Location: $location", true, $status);}
endif;

我很难弄清楚这个问题,因为我不是程序员。有什么地方出了问题吗? 请帮帮我...


嗨,保罗,你好!很抱歉,你能用英语翻译一下吗?那我该怎么做呢? - Ben Daggers
pluggable.php是什么?为什么需要它?看起来应该在functions.php之前包含它,因为它试图设置HTTP头,而这些需要在开始输出HTML之前设置。 - Paul Grime
保罗,我不知道这里该怎么做,我只知道 <?php if(function_exists('register_sidebar'))register_sidebar();?> 是用来给我的侧边栏添加小部件的。抱歉,我不知道其他的了。 - Ben Daggers
2个回答

88

您的主题正在向浏览器输出(文本),但出于某种原因,WordPress在整个页面呈现之前使用wp_redirect将用户重定向(离开该页面)。您不能开始打印输出,然后重定向,否则您会得到所见的错误。这就是Paul Grime在他的评论中提到的内容。

Ken White通过引用一个类似问题的帖子进行了评论。我的经验表明,可以通过缓冲脚本的输出来解决这个问题。

在您主题的functions.php文件中(每次加载您主题的页面时都会被包含),请添加以下内容:

//allow redirection, even if my theme starts to send output to the browser
add_action('init', 'do_output_buffer');
function do_output_buffer() {
        ob_start();
}

现在,即使您的主题开始向浏览器发送输入,PHP也不会发送该文本,直到页面完全加载,这使得WordPress可以根据自己的逻辑重定向用户(如果必要)。


1
@BenDaggers 请将此答案标记为正确或评论说明原因。谢谢。 - hitautodestruct
12
这会有任何副作用吗? - papaiatis
5
是的,这会产生副作用,其中最明显的是内存使用和较慢的网站响应速度,因为整个页面在发送任何内容之前必须先进行呈现。 - Peter Wooster
太酷了!我在使用这个插件(授权GitHub应用程序)时遇到了wp_redirect()问题,但这个解决方法很有效。当然,这只是一个权宜之计,但仍然非常有效。 - brasofilo
哇!谢谢你,我在尝试在我的自定义插件中进行简单的重定向时浪费了好几个小时!我感觉自己很蠢。 - Luiz Eduardo
显示剩余5条评论

21
如果你想从当前页面重定向到另一个页面,并且需要加上条件或者不需要条件,那么可以使用以下代码。例如你有两个页面A.php和B.php,并且当前在A.php页面上,当你点击按钮时想要前往B.php页面。
   if(isset($_POST['save_btn']))
    {
        //write some of your code here, if necessary
        echo'<script> window.location="B.php"; </script> ';
     }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接