I am doing the following in my plugin:
-
Register a custom admin page and in the callback function (the last parameter of
add_submenu_page) - Redirect to another page
However, when I open the custom admin page I get the following error:
Warning: Cannot modify header information - headers already sent by (output started at ..wp-adminincludestemplate.php:1637) in ..wp-includespluggable.php on line 878
Here’s the callback function:
function myplugin_callback(){
wp_redirect('http://google.com');
exit;
}
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You can’t redirect to another page, because WordPress has already rendered admin header and sidebar templates. If you really wish to redirect users to another page, you need to do it earlier, before header and sidebar are rendered. You can use action of following structure to redirect to another page:
load-{parent_page_slug}_page_{plugin_subpage_slug}
The full snippet:
define( 'WPSE8170_REDIRECT_PAGE_SLUG', 'wpse8170-redirect-page' );
add_action('admin_menu', 'register_my_custom_submenu_page');
function register_my_custom_submenu_page() {
add_submenu_page( 'tools.php', 'My Custom Redirect Page', 'Redirect Page', 'manage_options', WPSE8170_REDIRECT_PAGE_SLUG, 'wpse8170_redirect_page_callback' );
}
function wpse8170_redirect_page_callback() {
// ...
}
add_action( 'load-tools_page_' . WPSE8170_REDIRECT_PAGE_SLUG, 'wpse8170_mypage_redirect' );
function wpse8170_mypage_redirect() {
if ( WPSE8170_REDIRECT_PAGE_SLUG == filter_input( INPUT_GET, 'page' ) ) {
wp_redirect( 'http://google.com' );
exit;
}
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0