0

I need a function to tell me if a specific post (or a custom post type) has been visited by the current user or not. thank you.

0

You can add a special custom field when a logged user visits any page.

A way to do this without editing the template file, is to use the filter the_content

add_filter('the_content', 'wpse_259159');

function wpse_259159($content){

    // check the user ID
    $current_user = wp_get_current_user();
    if ( 0 == $current_user->ID ) {
      // Not logged in.
    } else {
    // Logged in so we want to know if the custom field exists
    global $post;
    $visit_meta = get_post_meta($post->ID, 'users_visit_'.$current_user->ID.'_'.$post_ID, true);

        if($visit_meta){
            // the custom field exist
            update_post_meta($post->ID, 'users_visit_'.$current_user->ID.'_'.$post_ID, $visit_meta+1);
        }else{
            update_post_meta($post->ID, 'users_visit_'.$current_user->ID.'_'.$post_ID, '1'); 
        }

    }
    return $content; 
}

With this way, I don't return any value or string in the content, and I write a custom field for each logged in user, depending on your needs (number of users and posts) this can be very bad for the database weight, so you can create an array of all user that visit the page. Adapt this to retrieve the value in the template if you need.

Hope it helps.

| improve this answer | |
  • is this better than a cookie ? – AbdelhakAj Mar 10 '17 at 21:03
  • Yes of course, a cookie is only store in the client browser, has an expiration and couldn't be use by the admin for statistiques or anything else. But you can combine cookies and custom-field. – Benoti Mar 10 '17 at 21:07

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.