Leave a Reply

2 comments

  1. You could create a new entry for the user meta data and update it on every admin pageload.

    Put the following in your theme’s functions.php or maybe wrap it into a plugin:

    function update_last_action_time() {
        $user = wp_get_current_user();
        update_user_meta($user->ID, 'last_action_time', current_time('mysql'));
    }
    add_action('admin_init', 'update_last_action_time');
    

    Of course, you could refine this (and thus lower the overhead) by restricting this to certain pages, for instance, the dashboard only.

    // Edit: you should use update_user_meta instead of the deprecated update_usermeta.

    // Edit, again

    In case you want to track users on the front-end, put this code in your desired template:

    if (is_user_logged_in()) {
        $user = wp_get_current_user();
        update_user_meta($user->ID, 'last_action_time', current_time('mysql'));
    }
    

    Again, to lower the overhead, I’d prefer putting this not into the footer.php file. I’d rather take home.php (if you have one), or check for particular requests (e.g., your home page, meaning: home_url() == 'http://'.$_SERVER['SERVER_NAME']). But as said before (meaning: below ;)), the overhead is, of course, okay when using it nonetheless in footer.php.

  2. Try the following code which creates a function display_last_login that retrieves the current user’s ID, fetches the last login timestamp from the transient storage, and displays it on the screen.

    function display_last_login() {
    $user = wp_get_current_user();
    $user_id = $user->ID;
    $last_login = get_transient( 'user_last_login_' . $user_id );
    if ( false === $last_login ) {
        $last_login = __( 'Never', 'textdomain' );
    } else {
        $last_login = date( 'j F Y, H:i:s', $last_login );
    }
    echo '<p>Last Login: ' . $last_login . '</p>';
    

    }
    add_action( ‘wp_login’, ‘set_user_last_login’ );
    function set_user_last_login( $user_login ) {
    $user = get_user_by( ‘login’, $user_login );
    $user_id = $user->ID;
    set_transient( ‘user_last_login_’ . $user_id, time() );
    }