Redirecting Users in WordPress with wp_redirect()

WordPress like to takeĀ controlĀ of the standard .htaccess redirect system, and it does a good job at it so I’m partial to let it keep doing that, but what if you want to redirect someone to another site it can get in the way at time (it seems that there is always something loading before you plugin because, well, there is). WordPress has a built in function to handle redirects for you using some voodoo magic thats buried in some random core file, the function is simple.

One Simple Function

The function requires both variables, the first is the full domain link to the new location you want to go to and the second is the redirect type (either 301 or 302 depending on what you want to accomplish). I’ve read that it has to be a 301 or 302 as other (like 404) seem to fail and only bring up a blank page but I havent tested that myself. You’ll want to load this on a wordpress action, as inline seems to not work (at least in my particular case, if anybody has gotten normal, none actions wp_redirect() to work let me know).

One Simple Question

Simple to use, but firing it off isn’t always quite as simple as throwing it anywhere you want. I played around with it a bit for some mobile detection (not on this site, although it is sad how bad that header behaves on mobile, I’ll have to do something about that at some point). The plugin would take you to page page within it’s directory, then load wp-load.php so I would both be automatically connected to the database, and so that I would be able to call plugin variables using the get_option() function.

You can find a semi-complete list of the word press action hooks on the WordPress Codex Action Reference page, the trick was picking one that loads earlier enough to not slow things down for the mobile visitor, but late enough that my call for include of wp-load.php wouldn’t fire it again, creating an infinite redirect loop. Eventually after trying several of the hooks I went with template_redirect. Fires off as soon as the template would be redirected back to the default if yours went missing, but doen’t fire off again since the custom pages don’t load the WP template system. Seems like the perfect spot and works great.

One Simple Example

Final code relating to the redirect looks something like this, it will simple take the person to an index.php file in the site folder of the plugin directory, but obviously that can be directed anywhere.

One Simple Conclusion

I’ve got the code up on Snipplr, and also now on github:gists. As always if you have any questions feel free to let me know here, or on the relevant google+ posting, I’ll try to get back to you. Theres no example because it would be pretty pointless (all it would do is take you to a different page) but I could make one if someone just has to see it in action.

Leave a Reply

Your email address will not be published. Required fields are marked *