php - Why does a header location on admin_head remove the query var I'm setting in the location?

admin2025-06-02  2

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?

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?

Share Improve this question asked Feb 25, 2019 at 18:53 bigdaveygeorgebigdaveygeorge 2074 silver badges12 bronze badges 1
  • 2 admin_head is much too late to output a header. – Jacob Peattie Commented Feb 26, 2019 at 0:41
Add a comment  | 

1 Answer 1

Reset to default 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.

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748865763a314369.html

最新回复(0)