在Wordpress中的自定义插件页面中重定向

Gha*_*Mir 1 php wordpress redirect wordpress-plugin

案例:我在页面中有一个表单,用户可以在一个简单的文本文件中添加某些值.现在,我想在成功添加值后重定向到同一页面.

读/写代码都很好用,我甚至放了重定向代码,但这会显示警告header information is already sent.

我试过的标题:

header("Location: some_url_here_in_same_site");
wp_redirect("some_url_here_in_same_site");
Run Code Online (Sandbox Code Playgroud)

我的表格代码:

if(isset($_POST['txtName'])}

    // form validation code here
    if(successful)
        wp_redirect("some_url_here_in_same_site");

}
Run Code Online (Sandbox Code Playgroud)

问题:

  • 如何在我们的插件中提交表单后在wordpress中进行重定向?
  • ob_start 不会工作,所以也不要建议我这样做

Gha*_*Mir 7

好的,我设法使用Hooks.我使用下面的代码进行了重定向.请注意,表单操作设置为admin-post.php

<form action="admin-post.php" name="frmHardware" id="frmHardware" method="post">
    <!-- form elements -->
    <!-- Essential field for hook -->
    <input type="hidden" name="action" value="save_hw" />
</form>
Run Code Online (Sandbox Code Playgroud)

然后在我的插件的主文件中,我添加了以下内容:

add_action('admin_init', 'RAGLD_dashboard_hardware_init' ); // action hook add/remove hardware
Run Code Online (Sandbox Code Playgroud)

其中,函数定义如下:另请注意,第一个参数派生自admin_post一个保留字与action上面表格中的隐藏字段组合.

function RAGLD_dashboard_hardware_init() {
    // checking for form submission when new hardware is added
    add_action( 'admin_post_save_hw', 'RAGLD_process_hw_form' );
}
Run Code Online (Sandbox Code Playgroud)

在上面提交表单的评估之后add_action,RAGLD_process_hw_form将调用函数,该函数用于验证表单条目并相应地采取操作/重定向.

function RAGLD_process_hw_form() {
    if (form_is_validated) {
        wp_redirect( add_query_arg( array('page' => 'ragld/edit-hardware', 'action'=> 'InvalidData'), admin_url() ));
    } else {
        //do something else
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我暂时想到的解决方案,如果你觉得它们更有效,你可以建议你的答案.