Redirect function inside a Shortcode

I am developing a free plugin for connection a external support system to WordPress to be able to authenticate users on WordPress.

For this, currently from the external system, the user is sent to WordPress’s login page with this at the end


My plugin then checks if the user is logged into WP, if not it shows the login form and after successful login, redirects them back to the 3rd party site.

The redirect is done using something like this: wp_redirect( $sso_url );

Now this works well, but I plan to offer a shortcode which could be added to a page the user chooses. Now once a user goes to this page, if they are logged in, they should be forwarded to the 3rd party site, if not, then to the login page.

Is there a way you could suggest wp_redirect to work inside a shortcode?

Solutions Collecting From Web of "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();
    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

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.

wp_redirect() performs redirect via HTTP headers so technically it won’t (or at least shouldn’t) work after page output started. So you can’t just use this function in shortcode.

Which doesn’t mean however you can’t use shortcode to control it. You could check for fitting conditions (if is page and page contains shortcode) before output started (somewhere around template_redirect hook) and perform redirect then.

Another option would be to output conditionally JavaScript that will perform redirect after page have loaded.

Add ob_start(); at the top of plugin or add in class construct function
Example :

function __construct() {