TRANSITION_POST_STATUS操作中的回显行导致“无法修改标头信息-标头已由”

时间:2015-03-15 作者:rkoller

我试着用transition_post_status. 我想在里面设置一些条件语句。为了看看是否一切正常,我想放置一个调试语句。问题是,一旦我设置了echo语句,我就会得到输出以及两条警告消息:

Error

Warning: Cannot modify header information - headers already sent by (output started at /Applications/MAMP/htdocs/sandbox/wp-content/plugins/media-meta-require/media-meta-require.php:193) in /Applications/MAMP/htdocs/sandbox/wp-admin/post.php on line 233

Warning: Cannot modify header information - headers already sent by (output started at /Applications/MAMP/htdocs/sandbox/wp-content/plugins/media-meta-require/media-meta-require.php:193) in /Applications/MAMP/htdocs/sandbox/wp-includes/pluggable.php on line 1178
无论我如何调用错误字符串,错误都会出现。使用普通回显字符串:

function mmr_attachment_check( $new_status, $old_status, $post ) {
    if( $new_status === \'publish\' ) {
        echo \'Error\';
    }
}
add_action( \'transition_post_status\', \'mmr_attachment_check\', 10, 3 );
使用包含html元素的回显:

function mmr_attachment_check( $new_status, $old_status, $post ) {
    if( $new_status === \'publish\' ) {
        echo \'<div class="error"><p>Error</p></div>\';
    }
}
add_action( \'transition_post_status\', \'mmr_attachment_check\', 10, 3 );
或者如果调用外部函数:

function mmr_attachment_check( $new_status, $old_status, $post ) {
    if( $new_status === \'publish\' ) {
        mmr_admin_notice();
    }
}
add_action( \'transition_post_status\', \'mmr_attachment_check\', 10, 3 );

function mmr_admin_notice() {
    global $pagenow;
    if( $pagenow == \'post.php\') {
        echo \'<div class="error"><p>Error</p></div>\';
    }
}
只要我注释掉与echo相关的行,它就会毫无错误地通过。我还参考了wp故障排除文档problem. 但在我的例子中,我找不到任何可能导致这种行为的空格或类似物/

1 个回复
最合适的回答,由SO网友:Pieter Goosen 整理而成

您看到的错误消息对于该操作来说是正常的。到transition_post_status 钩子激发时,HTTP页标头已发送。只需在钩子中回显错误消息,就像transition_post_status 它从未打算将任何输出回显到浏览器,正如您所做的那样,您实际上是在尝试将错误消息插入到此页面标题中,从而导致错误消息显示出来。

transition_post_status 应用于在成功时启动挂钩函数或执行特定任务,而不是将输出回显到浏览器。以下内容未经测试,但您可以尝试以下内容

add_action( \'transition_post_status\', function ( $new_status, $old_status, $post ) {
    if( $new_status === \'publish\' ) {
        add_action( \'admin_head\', function () {
            echo \'To test if we get this message without headers already sent error message\';
        }, PHP_INT_MAX );
    }, 10, 3 );

结束

相关推荐

wp_list_tables bulk actions

如何在扩展的WP\\U List\\U表中触发批量操作。我一直在将以下批量操作添加到may table的选择框中,但在Apply上不会发生任何事情下面是我如何添加批量操作的function get_bulk_actions() { $actions = array( \'delete\' => \'Delete\', \'parsing\' => \'Parsen\' );