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?
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.
admin_head
is much too late to output a header. – Jacob Peattie Commented Feb 26, 2019 at 0:41