Leave a Reply

8 comments

  1. In case you want to know if the user is logged in at the current moment, try this. The other answers check if the user is logged in or not when the page loaded, not the time when you’re running the javascript. The user could have logged in in a separate tab, for instance.

    Put this in your javascript

    var data = {
        action: 'is_user_logged_in'
    };
    
    jQuery.post(ajaxurl, data, function(response) {
        if(response == 'yes') {
            // user is logged in, do your stuff here
        } else {
            // user is not logged in, show login form here
        }
    });
    

    Put this in your functions.php

    function ajax_check_user_logged_in() {
        echo is_user_logged_in()?'yes':'no';
        die();
    }
    add_action('wp_ajax_is_user_logged_in', 'ajax_check_user_logged_in');
    add_action('wp_ajax_nopriv_is_user_logged_in', 'ajax_check_user_logged_in');
    
  2. Check the class attribute for body: If the theme is using body_class() the body has a class named logged-in for users that are logged in. Be aware the function can be used on the element html too.

    Example with jQuery:

    if(jQuery('body').hasClass('logged-in')){
        // Do something
    }
    

    Example with pure JavaScript:

    if (document.body.classList.contains('logged-in')) {
        // do something
    }
    

    You can also just use is_user_logged_in() as a condition to enqueue or print the script.

  3. Please add body_class() to your html body

    <body <?php body_class(); ?>>
       //your html code
    </body>
    

    This will add logged-in for logged user then you can use following jquery code to execute your custom juqery code only for logged user.

    if ($('body').hasClass('logged-in')) {
           //execute your jquery code.
    }
    
  4. Please note that none of the above examples are reliable in case you use a page cacheing plugin, then the code in body tag will be static. Also there is a simple way to do this (with no extra query to ajax which is not optimal)

    If you want to test user logged in state with javascript, you can use this code to set cookie when user logged in and delete cookie when user logged out. Add this eg. to your theme functions.php

    function login_function() {
        setcookie('wp_user_logged_in', 1, time() + 31556926, '/');
        $_COOKIE['wp_user_logged_in'] = 1;
    }
    add_action('wp_login', 'login_function');
    
    function logout_function() {
        unset($_COOKIE['wp_user_logged_in']);
        setcookie('wp_user_logged_in', null, -1, '/');
    }
    add_action('wp_logout', 'logout_function');
    

    Then its a simple test of cookie in javascript.

    if (document.cookie.indexOf('wp_user_logged_in') !== -1) {
        //do something when user logged in
    } else {
        //do something when user logged out
    }
    
  5. Another example, in case you want to use it for AJAX calls.

    // Simplified... please note, that all names/vars/etc. in my class got unique names.
    // ...the same goes for the script handler.
    class wpse69814_example
    {
        public $response;
    
        public function __construct()
        {
            add_action( 'wp_enqueue_scripts', array( $this, 'enqueue' ) );
            add_action( 'wp_enqueue_scripts', array( $this, 'localize' ), 20 );
        }
    
        public function enqueue()
        {
            wp_enqueue_script(
                'wpse69814_handler',
                plugins_url( 'url/to/file.js', __FILE__ ),
                array( 'jquery' ),
                filemtime( plugins_dir_path( __FILE__ ).'/path/to/file.js' ),
                true
            );
        }
    
        public function localize()
        {
            wp_localize_script( 'wpse69814_handler, 'wpse69814_object', array(
                'ajaxurl'    => admin_url( 'admin-ajax.php' ),
                'ajax_nonce' => wp_create_nonce( 'wpse69814_nonce' ),
                'action'     => 'wpse69814-handler-action',
                'data'       => array(
                   'is_user_logged_in' => is_user_logged_in(),
                )
             )
    
        }
    }
    
  6. Thanks to this post and another post, I found a solution to my issue. I’m just posting in case anyone might find it useful.

    Works on current WordPress sites

    This code checks if user is logged or not using jquery. If the user is NOT logged in, it prevents the user from right clicking content and copying images and text.

    $(document).ready(function(){
    
        // if user is not logged in...
        if (!document.querySelector('body.logged-in')){
            //lock all content
            disableSelection(document.body);
            // disable image click
            $('img').bind('contextmenu', function(e){return false;}); 
            console.log('hello');
        }
    
        // function to lock all content
        function disableSelection(target){
            $(function() {
                 $(this).bind("contextmenu", function(e) {
                     e.preventDefault();
                 });
             }); 
             if (typeof target.onselectstart!="undefined") //For IE 
                  target.onselectstart=function(){return false}
             else if (typeof target.style.MozUserSelect!="undefined") //For Firefox
                  target.style.MozUserSelect="none"
             else //All other route (For Opera)
                  target.onmousedown=function(){return false}
             target.style.cursor = "default";
        }
    })
    
  7. I appreciated all the answers but localize script or checking the css class would be, in my opinion, not the best practice as the css class checking is not 100% reliable and the localize script function is, as the name suggests, localising.

    After WordPress 4.5 the best solution would be adding an inline script as follows:

    <?php
    
    function detect_login() {
      $isLoggedIn = is_user_logged_in();
      wp_register_script( 'detect_login', '' );
      wp_enqueue_script( 'detect_login');
      wp_add_inline_script( 'detect_login', "var isLoggedIn = $isLoggedIn" );
    }
    
    add_action( 'wp_enqueue_scripts', 'detect_login' );
    

    And then obviously check the global scope which is now sadly polluted by our global var isLoggedIn as follows: window.isLoggedIn