0

I am working a project and I've decided to develop a custom plugin for it and I want it to show every users page visit count somewhere in the footer.(For example, if a user clicks on a page, it would show in the Footer - "you have visited this page 1 time" and if he refreshes it would show 2 times)

Until now I have got something to work but it shows the total users online on the page, but I want to store in a couple of weeks long cookie the user's activity and keep track of his page visits.

    //  Get user online
    public static function WTVCP_get_users_online()
    {
        $base      = "base_sessions.dat";
        $last_time = time() - 120;
        touch($base);
        $file = file($base);

        $output = '';

        $id = session_id();
        if ($id !== '') {
            $res_file = [];

            foreach ($file as $line) {
                list($sid, $utime) = explode('|', $line);

                if ($utime > $last_time) {
                    $res_file[$sid] = trim($sid) . '|' . trim($utime) . PHP_EOL;
                }
            }

            $res_file[$id] = trim($id) . '|' . time() . PHP_EOL;
            file_put_contents($base, $res_file, LOCK_EX);
            $count_users = count($res_file);
            $count_users = (string)number_format($count_users);
            $symbols     = str_split($count_users);

            foreach ($symbols as $symbol) {
                if ($symbol == ',') {
                    $output .= ",";
                } else {
                    $output .= "<span>$symbol</span>";
                }
            }
        }

        return $output;
    }

this is my main code that shows the user count right now. Is there any way to modify it to make it based on Unique sessions or something like that? Any advice would be much appreciated. Thank you!

1
  • note that PHP sessions are turned off on a lot of WordPress hosts, and are incompatible with many CDN systems and caching systems. Such a site can never be cached if you're doing this on the server. You're best doing this client side, and you can't trust that this will ever be reliable or foolproof ( this system breaks down the moment you open multiple tabs at the same time and is vulnerable to race conditions and resource exhaustion attacks )
    – Tom J Nowell
    Aug 20, 2022 at 16:19

1 Answer 1

0

My guess is that the user must be logged in? If that is the case you can simply store the page hits as metadata doing something like this:

add_shortcode('pagehits', 'showPageHits');

function showPageHits($attributes)
{
  /** @var \WP_Query $wp_query */
  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]);
}

If the user is not logged in the above will store a transient entry where the key is created based on the clients ip address e.g. pagehits_192.0.0.1.

14
  • Yes, the user will not be logged in. For every user that just enters the page.
    – Urus221
    Aug 20, 2022 at 14:10
  • @Urus221 - Ok, I can update my answer and add some solution for that as well. Aug 20, 2022 at 14:11
  • I would so appreciate that please because I have so much problems with storing the data
    – Urus221
    Aug 20, 2022 at 14:15
  • 1
    Thank you so so much for your time and your answer. It works perfectly. I would've upvoted but I do not have the Reputation points yet but everyone should upvote the answer because it works perfectly. Have a great great day!
    – Urus221
    Aug 20, 2022 at 16:41
  • 1
    You are awesome man . I looked at the code and saw "pages" was not mentioned anywhere until there but i didnt know for sure. Thank you for the amanzingly fast answer.
    – Urus221
    Aug 25, 2022 at 17:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.