WordPress wp_redirect() doesn’t work

I am inserting a piece of code to my website that includes a redirect statement. Everything works fine except the wp_redirect();. The following warning message appears.

Cannot modify header information - headers already sent by (output started at /home/xyz.com/b14_32999707/htdocs/wp-includes/class-wp-styles.php:350) in /home/xyz.com/b14_32999707/htdocs/wp-includes/pluggable.php on line 1416

Following is line 1416 of the mentioned file.

Read More
$x_redirect_by = apply_filters( 'x_redirect_by', $x_redirect_by, $status, $location );
if ( is_string( $x_redirect_by ) ) {
    header( "X-Redirect-By: $x_redirect_by" ); //Line 1416
}

header( "Location: $location", true, $status );

return true;

Tried each and every solution available on the web but nothing works except the JavaScript redirect which I don’t want to use. Even a very simple php code like the following doesn’t work.

<?php
if(...){
  wp_redirect('http://www.my-site.com/my-page/');
  exit();
}

Related posts

Leave a Reply

1 comment

  1. The problem is not what you are doing, but when you are doing it.

    When your browser requests a webpage, that webpage arrives with a set of HTTP headers, followed by a HTTP body that contains the HTML. Redirection is done via a HTTP header. The moment you echo, or printf or send any form of HTML, or even blank space PHP will send HTTP headers telling the browser to expect a webpage, then it will start sending the HTTP body. When this happens your opportunity to redirect has gone, and any attempt to send a HTTP header will give you the error in your question.

    For this reason, you cannot trigger http redirects in shortcodes, widgets, templates, etc.

    Instead, do it earlier, before output begins, preferably in a hook, e.g.

    add_action( 'init', 'asmat_maybe_redirect' );
    function asmat_maybe_redirect() : void {
        if ( ... ) {
            wp_redirect( 'http://www.my-site.com/my-page/' );
            exit();
        }
    }
    

    Additionally, if that redirect is to somewhere else on the same site, use wp_safe_redirect instead. But whatever you do, it must happen early before any output occurs.