wp_redirect not working from shortcode function

Whenever I use wp_redirect(plugins_url('account/login')); in a shortcode function I get the following error:

Warning: Cannot modify header information - headers already sent by ...

Is there any way to redirect from there? My guess would to echo some Javascript that does the redirect from me, but I was wondering whether there would be a server-side implementation of this.

Related posts

2 comments

  1. Why does it need to be a Shortcode? Looks like a XY Problem.

    You’re already inserting the shortcode manually in the edit screen. Use a Custom Field instead and hook earlier where you can actually do the redirect.

    enter image description here

    add_action( 'template_redirect', function(){
        global $post;
        $redirect = get_post_meta( $post->ID, 'redirect', true );
        if( $redirect )
        {
            wp_redirect( admin_url( 'profile.php' ) );
            exit;
        }
    });
    
  2. To redirect to another page you need to set an http header. To set an header it has to be the first thing that is output to the browser.

    You are trying to set an header when something already has been output to the browser, that’s why you get the warning and the redirect doesn’t work.

    You need to change your implementation so that the redirect is triggered before anything got output. So you should hook it to init or any other action that happens before output.

    This can also happen due to another plugin which incorrectly outputs something when it shouldn’t.

Comments are closed.