Can i check if user is doing any ajax request?

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