【问题标题】:How can I set a php header redirect in a wordpress admin page如何在 wordpress 管理页面中设置 php 标头重定向
【发布时间】:2013-12-17 04:46:09
【问题描述】:

编辑:我已扩展示例代码以包含一个基本用例。

我正在尝试为 wordpress 中的插件创建管理页面。我已经使用 codex 中的说明成功地制作了一个简单的管理页面。但是,我目前被卡住了。我正在尝试使用

header("Location: /myLocation");

调用,但我无法设置标题,因为显然在加载管理页面时,已经输出了其他 HTML。我想使用标头重定向,以便我为管理页面构建的表单处理程序可以使用 POST 到 GET 模式。 (用post将表单回发给自己,处理post数据,header用get重定向回自己,所以它可以防止重新发布和表单重新提交警告)

有什么方法可以修改我的设置,以便我能够拨打header()?

我按照这里的教程 http://codex.wordpress.org/Adding_Administration_Menus

这是我的代码,目前在mu-plugin 中。将其作为常规插件是否会对我使用header()? 的能力产生任何影响,如果可能的话,我宁愿坚持使用mu-plugin,但如果必须,我会使用常规插件。

这是代码,除了对header() 的调用外,一切正常。它只是教程中给出的示例,其中包含我自己的一些文本。

感谢阅读!

<?php
/** Step 2 (from text above). */
add_action('admin_menu', 'my_plugin_menu');

/** Step 1. */
function my_plugin_menu() {
    add_menu_page('My Plugin Options', 'Manage Articles', 'manage_options', 'manageArticles', 'manage_articles');
}

/** Step 3. */
function manage_articles() {
    if (!current_user_can('manage_options')) {
        wp_die(__('You do not have sufficient permissions to access this page.'));
    }
?>

<?php

//this block of code is an example of what I am trying to do

if (isset($_POST['formSubmit']) && $_POST['formSubmit']==='true')
{
global $wpdb;
$wpdb->query("UPDATE myTable set name='{$_POST['something']}' where id='{$_POST['id']}'");
header("Location: manageArticles?updated");
}
if (isset($_GET['updated']))
{
echo "you have updated the table!";
}

    ?>
    My admin page
    <form name="theForm" action="" method="post">
        Something: <input type="text" value="something" name="something"><br>
        Row ID: <input type="text" value="1" name="id"><br>
        <input type="hidden" value="true" name="formSubmit">
        <input type="submit">
    </form>
    <?php
}
?>

【问题讨论】:

  • 你可以尝试将ob_start();放在你的第一个&lt;?php下面
  • 已经输出的html来自wordpress核心,而不是我的页面,所以我自己的脚本中的输出缓冲不会有任何效果。我想我需要使用钩子,但除此之外我知道的不多。
  • @chiliNUT 为什么要在 manage_articles 中进行重定向?那么如果用户点击管理文章菜单应该怎么做呢?
  • 您必须为早期运行的操作之一注册一个操作/钩子回调(或任何 Wordpress 所称的回调),检测需要重定向的条件,然后发出 位置标题和退出。
  • @Sabari 我已经编辑了我的问题以包含一个用例。

标签: php wordpress plugins header postback


【解决方案1】:

所以...我还有更多关于钩子的知识要学习。由于这是一个mu-plugin,根据管理员挂钩列表here,我可以使用muplugins_loaded hook

所以把它放在插件的顶部

<?php
add_action('muplugins_loaded', 'my_plugin_override');

function my_plugin_override() {
    // your code here
    if (isset($_POST['formSubmit']) && $_POST['formSubmit'] === 'true') {
        global $wpdb;
        $wpdb->query("UPDATE myTable set name='{$_POST['something']}' where id='{$_POST['id']}'");
        header("Location: manageArticles?updated");
    }
    if (isset($_GET['updated'])) {
        echo "you have updated the table!";
    }
}
?>

<?php
//the rest of the code...
/** Step 2 (from text above). */
//......

【讨论】:

    猜你喜欢
    • 2019-05-22
    • 2017-07-23
    • 2011-02-06
    • 2010-10-04
    • 1970-01-01
    • 1970-01-01
    • 2016-05-16
    • 2017-09-19
    • 1970-01-01
    相关资源
    最近更新 更多