2

I want to call this function in JavaScript:

http://codex.wordpress.org/Function_Reference/is_user_logged_in

But the examples are only with PHP. When that JavaScript function is called I want to check if the user is logged and send a message / redirect if not.

Is there a way to do this?

0

2 Answers 2

5

Add this in your functions.php

function check_login() {
    $return['loggedin'] = false;  
    if ( is_user_logged_in() ) {
        $return['loggedin'] = true;    
    }
    echo json_encode($return);
    die();
}
add_action('wp_ajax_check_login', 'check_login');
add_action('wp_ajax_nopriv_check_login', 'check_login');

Add this to your custom JS code

$.ajax({
    url : YOUR_AJAX_URL, // "/wp-admin/admin-ajax.php"
    type : "GET",
    dataType : "json",
    cache : false,
    data : {
        action : 'check_login'
    },
    success : function (json) {
        if (json.loggedin) {
            alert("Loggedin");
        }
    }
});
Sign up to request clarification or add additional context in comments.

Comments

4

You can wrap javascript code in between php code like below

<script>
$('#checkLogin').click(function() {
    <?php if (!is_user_logged_in()): ?>
    alert('Please login to access this page');
    location = 'http://www.example.com';
    <?php else: ?>
    alert('You are logged in');
    <?php endif; ?>
});
</script>

5 Comments

but this only happens if I click on a div
@user2469440 - what do you mean? You could just do <script> var loggedIn = <?php echo is_user_logged_in(); ?>; </script> then use it later: if(loggedIn){ /* do stuff * / } else { /* redirect */}.
Maybe im doing it wrong this what I was thinking: I have a div that onclicked will update mysql table, so I have already stored if there is a user or not BUT when I click on that div I still want to do the mysql update. So I though I had to call a javascript function that would do the mysql update.
Code updated, you can also use @Joe method, which can be used at multiple place.
I've been searching and I guess I really need to use ajax. Since I want to update the page without having to reload :| I guess im learning something new today

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.