0

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?

1 Answer 1

0

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>
7
  • You pass the new $location value to JavaScript. I made an update to my answer with an oversimplified example for that.
    – fuxia
    Commented Nov 23, 2012 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
    Commented Nov 23, 2012 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.
    – fuxia
    Commented Nov 23, 2012 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.
    – fuxia
    Commented Nov 23, 2012 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
    Commented Nov 23, 2012 at 10:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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