2

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?

yivi
  • 42,438
  • 18
  • 116
  • 138
lukeseager
  • 2,365
  • 11
  • 37
  • 57

1 Answers1

2

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.

yivi
  • 42,438
  • 18
  • 116
  • 138
  • Thanks, apologies I probably gave too much information around the problem. That’s perfect, i’ll test it out and see how I get on. But yes, I just needed a stear on OOP programming I guess, thanks. – lukeseager Sep 11 '18 at 12:00
  • Yep, just tested it now and I'm able to use the update method now. Thanks for the help! – lukeseager Sep 12 '18 at 17:07