Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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
add comment

1 Answer

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:

<?php

$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:

<script>
var isLoggedIn = <?php print is_user_logged_in() ? 'true' : 'false'; ?>;
var redirectTo = '<?php print is_user_logged_in() ? admin_url( '/' ) : 'http://localhost'; ?>';
</script>
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
add comment

Your Answer

 
discard

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.