Ahad abasi rad
Ahad abasi rad

Reputation: 117

How to redirect in a wordpress custom plugin

I used wp_redirect() and header() for redirection after handle post request, but i get this error "Headers already sent." Is there another method for redirection?

Upvotes: 2

Views: 349

Answers (1)

firxworx
firxworx

Reputation: 1584

You are correct that wp_redirect() is the way to go. Your issue is that some part of your plugin or template is already sending a response back to the client's browser, i.e. the headers are already sent.

You need to call wp_redirect() before sending anything else, and send only that.

There are a ton of ways your code could be sending headers before the redirect call. For example, the issue could be something as simple as having a newline or whitespace before a PHP open tag <?php that gets interpreted as content to send back to the client's browser. By the time the interpreter would hit the wp_redirect() line, the headers would already have been sent, making it impossible for wp_redirect() to send a redirect header.

More on HTTP redirects: https://developer.mozilla.org/en-US/docs/Web/HTTP/Redirections

Note that it's common to follow a wp_redirect() line with an exit; line to ensure that WordPress/PHP execution stops and no further headers/content are sent back.

Upvotes: 1

Related Questions