How can I put a wp_redirect into a shortcode?

I have a typical shortcode which prints some html on a page. The shortcode will only be used on pages where visitors are logged in.

As a separate operation, I’ve been using a custom field to trigger an action which performs that test and then does the redirect.

But I was wondering if it was possible to combine that action into the shortcode and get rid of the custom field.

IOW: Can I make the shortcode print code in some tag in the header which tests to see if the visitor is logged in and if not, redirect them to the home page.

Eg.

function jchForm() { 
  add_action( 'no idea where this would go', 'my_redirect_function' );

  $s="<div class="clearboth">";
  $s .='<form id="my_form" action="" method="post">';
  $s .='<p><label>Your Name</label><input id="user_name" type="text"     name="user_name" class="text" value="" /></p>';
  $s .='<p><label>Your Email Address</label><input id="user_email" type="text" name="user_email" class="text" value="" /></p>';
  $s .='<p><input type="submit" id="my_submit" name="submit"     value="Register" /></p>';
  $s .='</form>';
 $s .='</div>';

return $s;

}

UPDATE: I tried this, per the has_shortcode() function reference, but although it fires, $post always returns NULL. How do I get this to print -before- any other html but -after- the query grabs $post?

function custom_shortcode_script() {
global $post;
if( is_user_logged_in() && has_shortcode( $post->post_content, 'jchForm') ) {
  var_dump($post->post_content); // always prints NULL
    wp_redirect( '/someplace');
  }
}

 add_action( 'init', 'custom_shortcode_script' );  

2 s
2

Shortcode functions are only called when the content of the visual editor is processed and displayed, so nothing in your shortcode function will run early enough.

Have a look at the has_shortcode function. If you hook in early enough to send headers and late enough for the query to be set up you can check if the content contains your shortcode and redirect then. The template_redirect hook is handy for this as it’s about the last hook to be called before your theme sends output to the browser, which triggers PHP to send the headers.

Leave a Comment