Can i check if user is doing any ajax request?

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?

1 Answer
1

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.

Leave a Comment