0

I have the following code which I thought would load the location with a query var of saved=1.

public function __construct() {

    add_action( 'admin_head', array( $this, 'test' ) );

}

public function test() {

    if( $_GET['test'] == 1 ) {

        header( "Location: admin.php?page=my-page&saved=1" );
        exit;

    }

}

I am expecting to go to:

http://localhost/test/wp-admin/admin.php?page=my-page&test=1

And the resulting page to be loaded as:

http://localhost/test/wp-admin/admin.php?page=my-page&saved=1

But the query var gets removed? Why?

  • 2
    admin_head is much too late to output a header. – Jacob Peattie Feb 26 at 0:41
0

If you want to perform any redirects, you have to send your header before site sends any output.

admin_head is an action that allows you to print your custom code inside <head> tag of admin sites. But if it's inside of <head>, then some output is already sent to the browser, so you can't perform any redirections any more.

As you can see here Actions Run During an Admin Page Request, the admin_head is called after the scripts and styles are already printed.

So you should run your code using some hook that is fired before any output is sent to the browser. You can use wp hook for example.

PS. Another thing is that you shouldn't use header( "Location: admin.php?page=my-page&saved=1" );. Using wp_redirect would be much nicer way to do this.

  • I have added this to action on current_screen, before headers sent and after I have the current screen global. Thanks for your help. – bigdaveygeorge Feb 26 at 19:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.