3

I make a custom user meta and its name is last_activity.

I use this meta to get the date of user last activity and I updated the meta each time user open a page using WordPress wp_head action.

My problem that user maybe does some actions by ajax without refresh the page so sure the last_activity meta will not be updated.

So my question is can I check if the current user is do any ajax request or not and if yes so do_action?

2

You'd be better off moving your function that updates the meta to a hook that runs on the front end and during AJAX calls. Then you don't need to bother about checking if the request is an AJAX request or not. init is a good choice for this:

function wpse_297026_update_user_activity() {
    update_user_meta( get_current_user_id(), 'last_activity', time() );
}
add_action( 'init', 'wpse_297026_update_user_activity' );

get_current_user_id() returns 0 if there's no user logged in, and update_user_meta() will fail silently (without hitting the database) if you try to set meta on user_id 0, so there's no need to check if a user is logged in.

All that being said, you mentioned wanting to store the date of last activity. How precise does this need to be? My example code is storing the time down to the second, but if you only need the day then updating the meta on AJAX requests seems unnecessary. I highly doubt you'll have many users visiting the site one day and then only making AJAX requests for 2 days.

7
  • Please, can you explain to me more about init action? You mean that init action is checking also the ajax requests? – Mido Mar 16 '18 at 16:42
  • The init hook is run whenever WordPress loads. Including on AJAX and REST requests. This article shows all the hooks run on each request. init is the earliest hook run after all themes and plugins have loaded and after the current user has been identified. – Jacob Peattie Mar 16 '18 at 16:45
  • Okay now I understand, I just have one another question let's say that I will sell my theme for people, using init action to update the current user activity will slow their sites if the site has huge amount of users? NOTE: I will make that not update the meta is the meta updated last 5 minutes. – Mido Mar 16 '18 at 16:50
  • and using init action is better or going into each system I made that using ajax request and add an action to update the meta? – Mido Mar 16 '18 at 16:51
  • Taking a record of user activity is not functionality that belongs in a theme, if you ask me. The performance impact will depend on how many logged in users there are. If users aren't signed in no database calls will be made. But yes, there could be an impact. – Jacob Peattie Mar 16 '18 at 16:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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