WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I want to check if a user is logged in. If he is, I want to redirect him to page A, and if he isn’t to page B.

The redirect should happen per JavaScript after a button has been clicked – so I need the status or the URL to be available in JavaScript. How can I get these data from WordPress into JavaScript?

share|improve this question
up vote 0 down vote accepted

To test if a user is logged in use is_user_logged_in().

To redirect a visitor use wp_redirect($location, $status = 302).

You can combine both:


$location = 'http://localhost';

if ( is_user_logged_in() )
    $location = admin_url( '/' );

wp_redirect( $location );

In JavaScript (sort of):

add_action( 'wp_footer', 'wpse_73701_button' );

function wpse_73701_button()
    $location = is_user_logged_in() ? admin_url( '/' ) : 'http://localhost';

    print "<button onclick='window.location.href=\"$location\"'>Click!</button>";

You could also just create JavaScript variables and use them in your scripts:

var isLoggedIn = <?php print is_user_logged_in() ? 'true' : 'false'; ?>;
var redirectTo = '<?php print is_user_logged_in() ? admin_url( '/' ) : 'http://localhost'; ?>';
share|improve this answer
You pass the new $location value to JavaScript. I made an update to my answer with an oversimplified example for that. – toscho Nov 23 '12 at 8:39
Thanks for Reply.i am new to wordpress.i have Html button<input type="button" value="Check Login"> how can i check on this button or can i write your function in function.php.pls suggest me steps to do this. – swapnil Nov 23 '12 at 9:17
I made another update, showing ho to populate JavaScript variables with the information. The question how these variables could be used in JavaScript is a separate one and on topic on Stack Overflow. – toscho Nov 23 '12 at 9:22
Make that a separate question please. Questions hidden in comments are not very useful, because the search engine will never find them. – toscho Nov 23 '12 at 9:36
Thanks your answer helpful to me.but can you explain just want to learn how can i call your suggested "function wpse_73701_button()" function on button click. – swapnil Nov 23 '12 at 10:08

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.