3

I have a page that is restricted to logged in users (say it's called '/authed-page'). When a non-authenticated user visits this page they are prompted to click a button to login and they are then taken to the login url: '/login'

Now after they login I want them to get redirected to the page they had been trying to visit, '/authed-url', but I can't figure out how to do this!

Things I've tried:

1) Declaring a function redirect_to_authed_url in my functions.php file like this

function redirect_to_authed_url( $redirect_to, $request, $user ) {
    return "/post-a-job";
}

Then in the template for authed-url.php when I detect the user isn't logged in I do this:

<?php add_filter( 'login_redirect', 'redirect_to_authed_url', 10, 3 ); ?>

However this doesn't work I think because the user presses a button which generates another http request which sends them to the '/login' url which means the redirect filter is lost.

2) Setting a cookie when someone visits '/authed-url' and they are not logged in called 'redirect_url'. Then I declare this in my theme's functions.php file

function redirect_request( $redirect_to, $request, $user ) {
    if (isset($_COOKIE['login_redirect']) && strpos($_COOKIE['login_redirect'], 'http') === false) {
        $redirect_url = $_COOKIE['login_redirect'];
        unset $_COOKIE['login_redirect'];
        return $redirect_url;
    } else {
        return('/');
    }
}

This doesn't seem to work because I can't figure out where to set the cookie. I keep getting the warning:

WARNING: CANNOT MODIFY HEADER INFORMATION - HEADERS ALREADY SENT

I feel like I must be missing something obvious. This should be a pretty common requirement no? Any ideas?

user1813867
  • 1,045
  • 1
  • 9
  • 17
  • possible duplicate of [How to fix "Headers already sent" error in PHP](http://stackoverflow.com/questions/8028957/how-to-fix-headers-already-sent-error-in-php) –  May 12 '15 at 04:13
  • try javascript in the page `/login` to redirect to `/authed-page` – ihsan May 12 '15 at 04:24

2 Answers2

2

You are able to append a URL encoded redirect_to variable to the login URL to get it to redirect after login.

For example:

http://www.example.com/wp-login.php?redirect_to=http%3A%2F%2Fwww.example.com%2Fauthed-url

That URL will redirect you to /authed-url after login.

jswat
  • 382
  • 1
  • 2
  • 11
-1

you can try this function to check user logging or not.

<?php
   if( is_user_logged_in() ) {
      echo 'your function for logging user';
   }else{
      echo 'your function for not logging user';
   }
?>
Tushal Bhanderi
  • 128
  • 2
  • 16