I want when any user open the post it count the post view. Currently i am using my custom function which is

<?php setPostViews(get_the_ID()); ?>

But the problem is that when user refresh the page it also count the post view. So how can i stop this adding views on page refresh.

3 Answers 3


One way to stop this would be to remember if this visitor has seen this page in the last x minutes. You can tackle that in multiple ways:

  • Use a cookie
  • Save visitor IP
  • Use sessions

Personally, I find using sessions just for counting pages is a bit silly.

Cookies can be a good solution, and you can set an expiration time if you want to re-count the same user after some time (even if that is a page refresh). But perhaps you don't want to inflict cookies on your visitors for this (also, there are European regulations on cookies).

Saving the IP address is not fool-proof (visitors can use proxy servers or dynamic IP addresses assigned by their ISP), but it is still a good solution for a simple counter. Since you already have a function to count your users, you could simply add their IP address while you're at it.

If you want this IP logging to expire after a certain time, like cookies can, you will also need to add a time stamp of when you added this IP address. You could then do two things:

  • Your counter script could check the timestamps in the log and ignore the entries which are older than x minutes.
  • You could set up a cronjob for a separate script which deletes entries from the log which are older than x minutes.

The latter is preferable if your log grows quickly.


You have couple of options:

Store user's ip address in session

if($_SESSION['last_ip_address']!= $_SESSION['REMOTE_ADDR']) :
    $_SESSION['last_ip_address'] = $_SESSION['REMOTE_ADDR'];

This will fire your function only if the ip address is different than the last stored. You can do the same with cookies:

if($_COOKIE['last_ip_address']!= $_SESSION['REMOTE_ADDR']) :
    $setcookie("last_ip_address", $_SESSION['REMOTE_ADDR']);

Apart from that you can do a lot of different checks, you can set the cookie which expires in an hour and check if it exists, you can additionally compare user's browser. Depending on how accurate you want it to be you should use one or more ways to secure that. Personally for just counting visitors SESSION should do just fine. Additional methods are usually used for things like "voting" to prevent double votes.


The right way "counting post views" is actually to don't Count them manually but for example use PIWIK / Google Analytics to track visitors and then over the API of that Tools read out the times that URL was viewed and Display the result.

That would really be more prezise than counting manually.

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.