WordPress: how to handle page redirects in shortcodes
2016, Jul 15
This is just a quick tip, something that I faced a while ago while working on a client’s website.
I had to develop a shortcode responsible to render a form and obviously after the submission I wanted to redirect the user to another url (following the POST/redirect/GET pattern).
It may seem easy but using something like wp_redirect directly in the shortcode rendering block may cause errors like this:
Warning: Cannot modify header information - headers already sent by ...
One possible (and very easy) solution is to register a function for the template_redirect hook and handle everything there. Something like this:
class my_shortcode{ | |
public function __construct() | |
{ | |
add_shortcode('my_shortcode', array($this, 'render_form')); | |
add_action( 'template_redirect', array($this, 'handle_form_post') ); | |
} | |
function render_form(){ | |
// guess what goes there 😀 | |
} | |
function handle_form_post(){ | |
if ( isset( $_POST[''my_shortcode_form_name'] ) ) { | |
$dest_url = 'set your url'; | |
wp_redirect($dest_url); | |
exit; | |
} | |
} | |
} |
of course don’t forget to create an instance of the class!