Plugin Settings Page: How to Redirect When Settings Are Saved

Plugins usually have their exclusive Settings Page. When I started writing wordpress plugin, I encountered one problem.

How to Redirect When Settings Are Saved

Setup Menu

add_menu_page('Test', 'Test', 'manage_options','test_settings_page',  array($this,'settings_page'));

Handle Settings

function settings_page(){
			$o = $this->get_option();
			if(wp_verify_nonce( $_POST['test_settings_page'], 'test_settings_page' )){
				$_POST = $this->clean_post();
				foreach($_POST as $k => $v)
					$o[$k] = $v;


The problem here is, when you call wp_redirect_to_current_page which calls wp_redirect, then you’ll encounter “Cannot modify header information – headers already sent by”.

That’s a classic problem and is self-explanatory. You redirect after some HTML code output. wp_redirect essentially invokes PHP header function which can only take place before HTML output. What’s the “HTML output” in our scenario? yep, when this error occurs, you’ll see WordPress left menu (Posts, Media, Links, etc,.) is already in there.


Back then, I have no clue how to deal with the redirect in a perfect way. So, I used meta refresh. This is not a good solution but it works most of the time. Yes, there is a slight chance that it won’t work, especially when you have lots of settings page. And then I tried to use ob_xxx functions to clean buffer before meta refresh. Well, that’s just make this solution more terrible.

Until now, I find a perfect solution to it.

Setup menu

add_menu_page('Test', 'Test', 'manage_options','test_settings_page',  array($this,'settings_page'));
add_action( "admin_action_test_settings_page", array($this, 'settings_page') );

Form Code in Settings Page

Well, I know, you may told me that WordPress has Settings API now. I know and the reason that I still stick to the traditional way is I can keep the html code in individual file and won’t mess with PHP.

Share and Enjoy

    FacebookTwitterGoogle PlusLinkedInStumbleUponPinterestRedditTumblrDiggEmailPrint

Related Posts