0

I would like to ask about the wp_redirect(); function. Before I ask this question, everything was working on both local and test servers. But right now, for some unknown reason, on my local wp_redirect is not working.

My current structure is this:

get_header();

...

wp_redirect($url);
exit();

This was also working with our previous programmer. If I declare my get_header after the wp_redirect, the wp_redirect function will work as intended. However, why is it that before, it was working? Btw, I read this SO Answer after I had this problem.

Were you able to work the wp_redirect after the get_header?

Note: I tried to rollback to previous version and on the old version, other part of the code that uses the same structure above no longer works.

The only difference between the environment was on my local, I accidentally dropped my table and reinstalled from scratch. Other than that, nothing comes to mind.

2 Answers 2

2

wp_redirect() works by sending a Location header. Headers cannot be sent after output has been sent to the browser. So you cannot output any HTML before calling wp_redirect().

Using wp_redirect() after get_header() never would have worked, which is why it doesn't work when you roll back. The only way it could've worked is if header.php was completely empty, so get_header() did not output HTML.

1
  • Thank you for answering. I might need to rearrange the code for efficiency so that on the production wont just suddenly stop working. Dec 14, 2021 at 9:17
0

You cannot redirect with wp_redirect() after the page content is rendered (this is what get_header() does).

So, you basically have 2 options-

  1. Place wp_redirect() before you include the header.

  2. With JavaScript-

<script type="text/javascript">
    window.location = 'https://google.com';
</script>
1
  • Thank you for answering. I might need to rearrange the code for efficiency so that on the production wont just suddenly stop working. Dec 14, 2021 at 9:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.