A few posts ago, I talked through the process of creating your custom WordPress admin page (and listed reasons as to why you may want to do this rather than using an existing API). One of the challenges of doing this, though, is knowing how to set up a WordPress admin redirect.

That is, let’s say that you specify some options – or perhaps you don’t – and you need to be able to display a custom message. Or maybe you want to do some processing on the backend and then show the results on the front-end.

Whatever the case, one of the challenges of not using one of the existing APIs is being able to correctly setup a WordPress admin redirect so that it takes the user back to the page they were on, but also does so with whatever messaging you want to display.

Safely Perform a WordPress Admin Redirect

Out-of-the-box, WordPress offers the redirect function; however, I’m more of a fan of using the safer option for security reasons.

Custom WordPress Admin Redirect with wp_safe_redirect

wp_safe_redirect offers the following:

Performs a safe (local) redirect, using wp_redirect().

You can, naturally, read more about this in the Codex but don’t miss this note, either:

wp_safe_redirect() does not exit automatically and should almost always be followed by exit.

 

With that said, I thought I’d share some code that will walk you through how to do a WordPress admin redirect back to the same page using best practices.

There are a few assumptions about the following code, though:

  • You’re using the WordPress Coding Standards,
  • You’re properly checking the referring URL and redirecting if it’s not valid,
  • You know whether or not to strip the ‘Settings Saved’ message from the query string (or not).

I’ll example more after the code:

A couple of quick notes:

  1. This function is a private function because I use it in the context of a class.
  2. There is an optional success parameter. This way, we can control whether or not the query string is added based on this function call.
  3. Next, it evaluates the value of success and then setting removes or adds the settings-saved query string argument (which is responsible for displaying the success message or not).

After that, it will perform the safe redirect using the resulting URL (with or without the settings saved message). And the reason that I like making sure the setting saved message is optional is because it gives you the ability to introduce your custom message.

That’s content, though, for a whole other post.