wp_redirect() – headers already sent

I am trying to use wp_redirect() to redirect the user after successfully submitting a signup form on the page.

It’s not working and shows the following error:

Warning: Cannot modify header information – headers already sent by
(output started at
/Applications/MAMP/htdocs/theme/wp-content/themes/test/header.php:10)
in /Applications/MAMP/htdocs/theme/wp-includes/pluggable.php on line
1178

I understand there has been already output before, that’s why it’s not working, but I have no clue how to make this work.

The signup form gets rendered by a function, and is submitted by another function, inside my functions.php.

if ( isset( $_POST['subscribe'] ) ) {
    // Submits the form and should then redirect
    wp_redirect("/thank-you/");
    exit;
}

Then both these functions are used where I want to show the signup form.

I’m afraid that’s not the best thing to do. I should be creating some action that does that, but I have no idea how to implement that. Most of the tutorials I found show the results directly on the same page and don’t require an additional redirect. Maybe that’s why they are working with functions inside the functions.php

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Found the answer (via)

Instead of using the function I added an action to “wp_loaded”, that makes sure that it gets loaded before any headers are sended.

<?php
add_action ('wp_loaded', 'my_custom_redirect');
function my_custom_redirect() {
    if ( isset( $_POST['subscribe'] ) ) {
        $redirect = 'http://example.com/redirect-example-url.html';
        wp_redirect($redirect);
        exit;
    }
}     
?>

Method 2

You have to use wp_redirect()
before get_header()
Then it will not show header error.

Method 3

add_action('template_redirect', function(){
if(isset($_POST['subscriptio'])){// make this condition such that it only matches when a registraiotn form get submitted
/**
 * do your stuff here
 */
wp_redirect();//....
}
});

Method 4

you can also do this

Instead of the below line

wp_redirect(“$url”);

write

echo("<script>location.href = '".$url."'</script>");

or

<?php <script><?php echo("location.href = '".$url."';");?></script>?>

It’ll definitely solve your problem.

Method 5

If you are creating a plugin, you can call ob_start(); at the beginning of the plugin code or ob_start(); at the top of the functions.php file before code begins

wp_redirect() - headers already sent


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x