• I’ve instantiated my plugin with a shortcode:
    add_shortcode('dv_code','dv_code');

    If the user is not logged in, I redirect to the login page:

    function dv_code(){
      $userID=get_current_user_id();
      if (!$userID){// 4.
        $loginURL=wp_login_url();
        wp_redirect($loginURL);
        exit();
      }
    }
    

    However, this generates “Headers already sent” errors:

    Warning: Cannot modify header information - headers already sent by (output started at /var/www/html/sites/wordpress/wp-includes/class.wp-styles.php:242) in /var/www/html/sites/wordpress/wp-includes/pluggable.php on line 1251

    and the login page does not appear.

    If I comment out the wp_redirect line, the errors do not appear, but, obviously, neither does the login page.

    Is there a way to accomplish this?

Viewing 2 replies - 1 through 2 (of 2 total)
  • Dion

    (@diondesigns)

    Once PHP has begun to output a page, it does not allow headers or cookies to be set. That means you cannot do a PHP-based redirect from a shortcode.

    You’ll need to re-think how to implement your plugin.

    Thread Starter dgcov

    (@dgcov)

    Thanks.

    I’m pretty sure that this is a fairly common scenario.

    My solution (in view of your suggestion) is to mimic the login page fields and hiddene-fields.

    
      $userID=get_current_user_id();
      if (!$userID){// 4.
          $loginURL=wp_login_url();
          $currentPage=$_SERVER['REQUEST_URI'];
          echo '<form name="loginform" id="loginform" action="'.$loginURL.'" method="post">
            <p>
              <label for="user_login">Username or Email Address<br />
              <input type="text" name="log" id="user_login" class="input" value="" size="20" autocapitalize="off" /></label>
            </p>
            <p>
              <label for="user_pass">Password<br />
              <input type="password" name="pwd" id="user_pass" class="input" value="" size="20" /></label>
            </p>
            <p class="forgetmenot">
              <label for="rememberme"><input name="rememberme" type="checkbox" id="rememberme" value="forever"  /> Remember Me</label></p>
            <p class="submit">
              <input type="submit" name="wp-submit" id="wp-submit" class="button button-primary button-large" value="Log In" />
              <input type="hidden" name="redirect_to" value="'.$currentPage.'" />
              <input type="hidden" name="testcookie" value="1" />
            </p>
          </form>';
        return;
    • This reply was modified 5 years, 8 months ago by dgcov. Reason: Define $currentPage redirect value without $_SERVER['HTTP_HOST']
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘redirect generates “Headers already sent” errors.’ is closed to new replies.