0

I am using wp_redirect() to redirect to a URL but it gives me the warning below and does not redirect. When should I use wp_redirect()? And does any one know how wp_redirect() works?

**[Fri Feb 28 03:58:36 2014] [error] [client 127.0.0.1] PHP Warning:
  Cannot modify header information - headers already sent by (output
  started at /home/virgo/public_html/others/sites/wepay/wp-content/
  themes/twentythirteen/header.php:43) in /home/virgo/public_html/o
  thers/sites/wepay/wp-includes/pluggable.php on line 875, referer: 
  http://127.0.0.1/others/sites/wepay/?page_id=15**
Rapptz
  • 20,807
  • 5
  • 72
  • 86
Azmat Karim Khan
  • 437
  • 5
  • 18
  • You can't use it after anything has been output, since it sends a redirect by using a `Location` header, and the headers come before the body of an HTTP message. – Paul Feb 27 '14 at 23:37
  • 2
    See http://stackoverflow.com/q/7381661/2126792 or http://stackoverflow.com/a/12770075/2126792. – pschueller Feb 27 '14 at 23:45

1 Answers1

1

Headers need to come first therefore you have to place this before any output. This includes error messages. If you run some code that has an issue which generates a notice this will prevent the redirect from running.

Take a look here: http://codex.wordpress.org/Plugin_API/Action_Reference

get_header is the latest point.

I'd suggest doing it once WP has been setup so you can use all conditionals including use of $post but still early. The most appropriate hook in my opinion would be 'wp'.

function wpse_redirect() {
    if ( ENTER A CONDITIONAL ) {
        wp_redirect( 'redirect-location' );
        exit;
    }
}
add_action( 'wp', 'wpse_redirect' );
Nathan Dawson
  • 18,138
  • 3
  • 52
  • 58