Tuesday, May 14, 2024
HomeWordPress Developmentredirect - wp_redirect() would not work

redirect – wp_redirect() would not work


The issue will not be what you might be doing, however when you might be doing it.

When your browser requests a webpage, that webpage arrives with a set of HTTP headers, adopted by a HTTP physique that incorporates the HTML. Redirection is finished by way of a HTTP header. The second you echo, or printf or ship any type of HTML, and even clean area PHP will ship HTTP headers telling the browser to anticipate a webpage, then it should begin sending the HTTP physique. When this occurs your alternative to redirect has gone, and any try and ship a HTTP header offers you the error in your query.

Because of this, you can not set off http redirects in shortcodes, widgets, templates, and many others.

As a substitute, do it earlier, earlier than output begins, ideally in a hook, e.g.

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

Moreover, if that redirect is to elsewhere on the identical website, use wp_safe_redirect as a substitute. However no matter you do, it should occur early earlier than any output happens.

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

Recent Comments