0

I've tested the following code in my function.php:

if ( $_GET['test'] ) {
  wp_redirect('https://google.com');
}

and it works, if I go to https://example.com/?test=true, I will be redirected to Google.

But I found out when I put wp_redirect() in a function hooked to some action, it won't work. Instead after its execution users will stay on the same page, and, in my case, some CSS files seems not being loaded.

Since I haven't figured out what kind of actions will trigger this behavior, it is hard for me to reproduce the problem and demonstrate it in a simple way. So I take some screen recording, hope that will help make sense of the problem I am experiencing: https://www.loom.com/share/4cfad90fde494fbd99db113c30b7555b

1
  • 1
    From what I could tell, the problem is because wp_redirect() (which uses the native header() function in PHP) should actually be called on page load, or before any output is sent (to the browser), but then you actually called the function after the submit button is (and other output are) rendered...
    – Sally CJ
    Commented Apr 9, 2022 at 0:05

1 Answer 1

0

As the docs say:

Note: wp_redirect() does not exit automatically, and should almost always be followed by a call to exit;:

wp_redirect( $url );
exit;
3
  • Did you watch my video? I did have exit in the code
    – shenkwen
    Commented Apr 8, 2022 at 22:14
  • 3
    You should put the exit in your code in the question then to avoid confusion. Or post the code you're having the problem with instead.
    – Rup
    Commented Apr 8, 2022 at 22:15
  • 2
    Firstly, it shouldn't be necessary to watch a video - you could have easily included the problematic code in your question. Secondly, though you do indeed include exit in your code, you do not include it in the right place. if (wp_redirect('https://google.com')) exit; means exit if the redirect was successful, which it wasn't because you didn't exit after it.
    – vancoder
    Commented Apr 8, 2022 at 22:25

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.