Advertisement
wpgenie

track post view using error_log and WP's debug.log

Oct 19th, 2021 (edited)
1,329
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 0.77 KB | None | 0 0
  1. /* visit us - https://wpgenie.org */
  2.  
  3. add_action( 'wp_head', 'slug_log_post_view' );
  4.  
  5. function slug_log_post_view() {
  6.    //set the ID of the post you want to track here:
  7.    $post_to_track = 42;
  8.  
  9.    //get the current post's ID & make sure it's a valid ID and it matches our ID
  10.    $id = get_queried_object_id();
  11.    if ( intval( $id ) > 0 && $post_to_track === $id ) {
  12.  
  13.       //check if current user is logged in and if so get the user ID
  14.       if ( is_user_logged_in() ) {
  15.          $user_id = get_current_user_id();
  16.          $user_id = 'a user with the ID ' . $user_id;
  17.       }
  18.       else{
  19.          $user_id = 'a user that was not logged in.';
  20.       }
  21.  
  22.       //log the information
  23.       error_log( "The post {$post_to_track} was accessed by {$user_id}" );
  24.  
  25.    }
  26.  
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement