Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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.

share|improve this question

2 Answers 2

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 is the 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 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, 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 time stamps 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.

share|improve this answer

You have couple of options:

Store user's ip address in session

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

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']) :
    setPostViews(get_the_ID());
    $setcookie("last_ip_address", $_SESSION['REMOTE_ADDR']);
endif;

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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