I'm creating a backend feature that calculated user's login sessions during the past 2 weeks.

This is easy enough to do by incrementing a custom user field when the user logs in using wp_login:

add_action('wp_login', 'calculate_login_sessions_custom', 99, 2);

This works well, and I was able to program it so that it doesn't count logins from the past 2 weeks. (The client only wants to see logins from the past 2 weeks).

The issue is, if someone logs out, I need to update these fields as well, or else someone will have the same login data for the past 2 weeks if they don't log back in (to trigger the function to remove old logins).

I know there's wp_logout, but what could I use if the user's session just ends?

  • Not sure this can be done. Unless you have some sort of 'beacon' that continually sends a 'probe' back to the host server, and you have some sort of continual process that checks for the probe. If the user goes to another site - or closes the tab - there is nothing that the user's browser sends back to your site to indicate they are 'gone'. Remember that browser sessions are 'stateless' - your site only knows something happens when the browser sends a request to your site. So don't know how you would 'sense' that a user has 'gone away'. Commented Aug 13, 2019 at 19:28

1 Answer 1


There is an auth_cookie_expired hook, but that's only going to fire if the user visits the site with an expired cookie.

Sessions don't "end" in the way you might be thinking. When users log in they get a session token with an expiration. When that expiration time passes, the token is no longer valid, but the token is only ever checked when the user visits the site. If the user logs in and then doesn't visit for 2 weeks, nothing happens in WordPress to log that user out. It only means that when they finally revisit the site, their token will have expired and WordPress will then require them to log in to get a new token. This is when auth_cookie_expired is fired.

So that answers your question about a hook firing when a session ends (TL;DR, there isn't one), but doesn't solve your problem. Unfortunately your question doesn't include enough information to be much help (it's a bit of an XY Problem, to be honest), but my suggestion would be to record all logins but including the expiration date. Then when you need to count or display the active sessions, you'd only count the sessions with a date that hasn't expired. You could couple that with the wp_logout and auth_cookie_expired hooks to completely remove sessions that are explicitly ended.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.