• Resolved NYCdev

    (@nycdev)


    I’m trying to add custom data to user sessions and I’m having some trouble.

    The first issue is I can’t figure out how to return 2 variables which are included in the original filter. As a result I’m getting this error:

    Missing argument 2 for add_last_activity_to_session()

    // on user login, add last_activity column
    add_filter('attach_session_information', 'add_last_activity_to_session');
    function add_last_activity_to_session( $session , $user_id ) {
        $session['last_activity'] = time();
    
        return $session;
    }

    The attach_session_information hook has 2 parameters: $session and $user_id. I’m guessing the error is happening as my function is only returning the session. How would I fix this?

    The second issue is how can I update the current session? I’m getting the error:

    Call to protected method WP_Session_Tokens::update_session() from context

    I think it’s from calling WP_Session_Tokens::update_session() but I don’t know how to avoid it. Is there a way of calling a private core WP function from functions.php

    /*
    * Update last activity for a user
    */
    add_action( 'init', 'update_session_activity' );
    function update_session_activity() {
        if ( !is_user_logged_in() ) {
            return false;
        }
    
        $sessions = WP_Session_Tokens::get_instance( get_current_user_id() );
        $token = wp_get_session_token();
        $current_user_session = $sessions->get( $token );
    
        $date_format = get_option( 'date_format', 'F j, Y' ) . ' @ ' . get_option( 'time_format', 'g:i A' );
    
        $current_user_session['last_activity'] = time();
    
        WP_Session_Tokens::update_session($token, $current_user_session);
    
        echo esc_html( date_i18n( $date_format, $current_user_session['last_activity'] ) );
    }

Viewing 1 replies (of 1 total)
  • Thread Starter NYCdev

    (@nycdev)

    figured it out.

    /*
    * Update last activity for a user
    */
    add_action( 'init', 'update_session_activity' );
    function update_session_activity() {
        if ( is_user_logged_in() ) {
            $manager = WP_Session_Tokens::get_instance( get_current_user_id() );
            $token = wp_get_session_token();
            $current_user_session = $manager->get( $token );
    
            // update last activity to current server time
            $current_user_session['last_activity'] = time();
    
            // update current session with new activity time
            $manager->update($token, $current_user_session);
        }
    }
Viewing 1 replies (of 1 total)
  • The topic ‘Updating current session data?’ is closed to new replies.