Amit

Code for unique user visit count on every page WordPress

add_shortcode('pagehits', 'showPageHits');

function showPageHits($attributes)
{

  global $wp_query;
  $page = $wp_query->get_queried_object_id();
  if (is_user_logged_in()) {
    $user = wp_get_current_user()->ID;
    $meta = get_user_meta($user, 'pagehits', true) ?: [
      'pages' => [
        $page => 0,
      ],
    ];
    $meta['pages'][$page]++;
    update_user_meta($user, 'pagehits', $meta);
  } else {
    $address = $_SERVER['HTTP_X_FORWARDED_FOR'] ?? $_SERVER['REMOTE_ADDR'];
    $cacheKey = 'pagehits_' . $address;
    $meta = get_transient($cacheKey) ?: [
      'page' => [
        $page => 0,
      ],
    ];
    $meta['pages'][$page]++;
    set_transient($cacheKey, $meta);
  }
  echo sprintf(_n('You have visited this page: %d time', 'You have visited this page: %s times', $meta['pages'][$page]), $meta['pages'][$page]);
}

Last Update on:March 5th, 2023 at 5:19 pm


Display Gallery Results Based on Current Year and previous year using CPT
Previous post