phpwordpressoopprocedural

Using WP_Session_Tokens class in a procedural WordPress Plugin


I'm writing a plugin for WordPress, in procedural PHP.

Anyway, in the plugin, I want to update a users WordPress Session Token, which is stored in the usermeta table.

Digging around, I've found a class which has some methods which I think will help me achieve my goal.

I've written a function, which has the correct data, updates the expiry time, and I'm just attempting to pass the update through WP_Session_Tokens.

But I get the error:

Using $this when not in object context in .../wp-includes/class-wp-session-tokens.php on line 166

My function is so:

function update_auth_cookie($user_login, $user) {

    $options = get_option('options_premium');
    $cookieTime = $options['cookieTime'];

    $sessionToken = wp_get_session_token();
    $verifier = hash('sha256', $sessionToken);

    $sessions = get_user_meta($user->ID, 'session_tokens', true);
    $sessions[$verifier]['expiration'] = $cookieTime;

    WP_Session_Tokens::update( $verifier, $sessions[$verifier]);

}
add_action('auth_cookie_valid', 'update_auth_cookie', 10, 2);

Is it possible to access a class through a function like this? If so, is it obvious what I'm doing wrong?


Solution

  • Your question is a bit broad, since the problem you are experiencing is not really related to the issue you are trying to solve (and addressing it would not necessarily give you the solution for what you are trying to do).

    But anyway: you are getting this error because you are invoking a method statically, and you should first instantiate WP_Session_Tokens and make the call dynamically.

    This are basic OOP concepts you should be aware of before trying to use objects, and are not much more difficult than regular PHP syntax.

    Something along the lines of:

    $wp_session_token = WP_Session_Tokens::get_instance($user->ID);
    $wp_session_token->update( $verifier, $sessions[$verifier]);
    

    Word to the wise: I'm not 100% that the above will work, and I do not have a WP installation handy to test it out, but it is at least syntactically/semantically correct and wont give you the error you are experiencing above.