I have no idea what I'm doing wrong, but I can't get the wp_redirect to actually redirect the page. I enabled the wp_debug to check for "header already sent" errors, but nothing. I installed the "Better HTTP Redirects" plugin to check the response, but it says 302 found.
If I check the wp_redirect response like this, it says "redirect success". But nothing really happens in the end, no errors show up either.
if ( wp_redirect( admin_url( 'admin.php?page=plugin_test&success=item_saved' ) ) ) {
echo 'redirect success';
} else {
echo 'no';
}
I tried to add ob_start to the init, and add an action for the admin_init and call ob_start from there but both made no difference. This is a stripped down version of the code I have, but it has the same problem.
What happens in the complete code is that the user fills in a form, adds the item and it is saved to the db. After that the user is redirected and a custom msg is shown. The whole script works fine, except for the last redirect.
class Submit_Test {
function __construct() {
add_action( 'init', array( $this, 'init' ) );
}
public function init() {
add_action( 'admin_menu', array( $this, 'create_admin_menu' ) );
}
public function create_admin_menu() {
add_menu_page( 'Plugin test', 'Menu', 'manage_options', 'plugin_test', array( $this, 'item_list' ) );
}
public function item_list() {
if ( isset( $_REQUEST['actions'] ) ) {
$this->add_item();
}
if ( isset( $_GET['success'] ) ) {
$this->show_success_notifications();
}
if ( $_GET['action']['add_item'] ) {
?>
<form method="post" action="" accept-charset="utf-8">
<input type="submit" name="actions" class="button-primary" value="add_item" />
</form>
<?php
} else {
?>
<ul>
<li><a href="http://localhost/wp-latest/wp-admin/admin.php?page=plugin_test">Current Item</a></li>
<li><a href="http://localhost/wp-latest/wp-admin/admin.php?page=plugin_test&action=add_item">Add Item</a></li>
</ul>
<?php
}
}
public function add_item() {
if ( wp_redirect( admin_url( 'admin.php?page=plugin_test&success=item_saved' ) ) ) {
echo 'redirect success';
} else {
echo 'no';
}
exit();
}
public function show_success_notifications() {
echo 'yes';
}
}
new Submit_Test;
Any ideas on how to get the redirect to work, and what i'm doing wrong? I'm out of ideas on what could be the problem here.
item_list
function will certainly run after output has already started, so this does seem like a headers already sent issue.wp_redirect()
is a pluggable function, so a plugin or a theme may have overridden it. Try disabling all your plugins and switch to a default theme like Twenty Twelve or Twenty Thirteen, and then see if the problem persists. (Admittedly, it's a long shot, but at the very least you'll be able to eliminate your plugins as the culprit.)header('Location: '.$newURL);
an option?