Redirect function inside a Shortcode

As @Rarst explains, shortcodes normally run too late for you to redirect from inside one. They usually run on the the_content hook which is well after content is sent to the browser. If you need to redirect based on the presence of a shortcode you need to check for that shortcode before any content leaves the server.

function pre_process_shortcode() {
  if (!is_singular()) return;
  global $post;
  if (!empty($post->post_content)) {
    $regex = get_shortcode_regex();
    preg_match_all("https://wordpress.stackexchange.com/".$regex."https://wordpress.stackexchange.com/",$post->post_content,$matches);
    if (!empty($matches[2]) && in_array('yourshortcodeslug',$matches[2]) && is_user_logged_in()) {
      // redirect to third party site
    } else {
      // login form or redirect to login page
    }
  }
}
add_action('template_redirect','pre_process_shortcode',1);

That is “proof of concept”. The particular conditions you need will likely be different. Note that that is a pretty “heavy” bit of processing. I would make sure it only runs where absolutely necessary.

Leave a Comment