【问题标题】:Set header redirect after page load页面加载后设置标题重定向
【发布时间】:2015-07-04 14:34:57
【问题描述】:

是否可以在设置标题后将用户重定向到正确的页面?

我在 WP 中开发了一个插件,允许用户管理他们在网站上创建的内容...例如,他们可以删除它或禁用 cmets。

作者选项出现在作者帖子的顶部...当用户单击按钮删除他们的帖子时,它会更改数据库中的一个值以软删除它:

$result = $this->db->update(
    $this->_table,
    array('active' => $status), // 0 / 1
    array('id' => $id)
);

if($result > 0)
{
    $this->setMessage('success', 'Post deleted.');
}
else
{
    $this->setMessage('error', 'Some error.');
}

页面似乎在显示消息时刷新,但帖子仍在显示。在出现“此帖子不存在消息”之前必须再次刷新页面。

我尝试了很多 WP 钩子来尝试在标头之前触发 wp_redirect,但我总是收到“标头已发送”错误。

我知道我正在使用 WP,但我认为这是 http/php 的限制,所以我决定在这里发布。

我想做这样的事情:

if($result > 0)
{
    header('Location: ...');
}
else
{
    $this->setMessage('error', 'Some error.');
}

不能使用输出缓冲。

这种类型的重定向在 Laravel 中是可用的,你甚至可以传递一个消息变量以显示在下一页上,所以它一定是可能的。

【问题讨论】:

  • 使用javascript重定向:window.location = "http://stackoverflow.com/questions/31221812/set-header-redirect-after-page-load" ;
  • <meta> 重定向比 JS 解决方法更通用。另见How to fix "Headers already sent" error in PHP
  • this 答案几乎就是你的答案

标签: php wordpress redirect


【解决方案1】:

使用 javascript 的简单且有效的解决方案。在我的项目中使用了这种类型的 reirection。从来没有问题:)

如果($结果> 0) { echo "";//enter location..example www.google.com, or profile.php etc } 别的 { $this->setMessage('error', '一些错误。'); }

【讨论】:

  • 为什么使用“parent.self.location”?我认为使用“location.reload()”就足够了(显然,如果它不在 iframe 内)。
  • 是的,如果它的 iframe 怎么办?只是为了 101% 完美 :D :) :)
  • 感谢这项工作...我发现 location.reload() 是 2 中更好的,不需要显式设置 URL。
  • @GoodBytes.. 不要忘记选择这个作为你的答案 :) 谢谢
【解决方案2】:

你可以使用javascripts

window.location.href='enter_your_url_here.php';

【讨论】:

    【解决方案3】:

    有两种方法可以做到这一点,

    第一个使用 Javascript 作为@Unni Babu 和@ash_8247 的答案。

    第二种方法是使用缓冲区

    //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();
    }
    

    看到这个post

    【讨论】:

      猜你喜欢
      • 2014-11-13
      • 1970-01-01
      • 2014-04-29
      • 1970-01-01
      • 2018-05-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-08
      相关资源
      最近更新 更多