Anyone know of a way to trick WordPress into doing a header location redirect. I have to check whether users are logged in or not, and if not redirect them to our organizations authorization system which is an external site.

I am getting output before my header() call, from WordPress outputting the queued scripts.

Warning: Cannot modify header information - headers already sent by (output started at /.../wp-includes/class.wp-scripts.php:128) in ...

I have a plugin, that had a class handler, that handles this with this method:

...
public function populateInfo($form) {
    $email = $this->hasEmail($form);
    /*$name = $this->hasName($form);
    $address = $this->hasAddress($form);
    $phone = $this->hasPhone($form);*/

    // let's get some auth info
    if($email !== false || $name !== false || $address !== false || $phone !== false) {
        $ldap = new LDAP();
        $webAuth = new Auth();
        $curPage="http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $webAuth->url = $curPage;
        if($webAuth->isLoggedIn()) {
            $ldap->search($webAuth->getID());

            // set up form variables
            $form['fields'][$email['key']]['defaultValue'] = $ldap->getEmail();
        } else {
            // this is where redirect fails
            wp_redirect($webAuth->login_url);
            return;
        }
    }

    return $form;
}
...

Update:

This method is called via a GravityForms filter:

add_filter('gform_pre_render', array($this, 'populateInfo'));

Which basically loads up info into a page form. The user must be logged in, in order for this form to populate (thus the $webAuth->isLoggedIn() check). Obviously I am aware that the headers are being output beforehand, my question is, how to properly workaround this in WordPress, so that I can redirect unauthorized users to the log in, without being brick-walled by preceding headers?

4 Answers
4

Your method is called too late. I don’t know how you call this method but you need to run it before output is sent to the browser– usually that means before get_header(). There are a number of hooks that can be used. For example (from https://wordpress.stackexchange.com/a/131210/21376):

add_action(
  'template_redirect',
  function() {
    if (is_single()) {
      wp_safe_redirect(home_url());
      exit;
    }
  }
);

Without more context, it is impossible to say exactly what the right hook is.

Leave a Reply

Your email address will not be published. Required fields are marked *