How to save Clicks of a download link button while it doesn’t matter if we refresh the page or again login/logout

The ideal way to do it is to have some identifier and save it in Database. But this can only happen if either user is logged in, in which case we can use, user meta to save the number of clicks, or we can use User IP and save it as transients. User IP again shall mean, that you need to get into hassles of policies and all, as IP is considered private information.

The strategy is to use Local Storage or Cookies, We could have used cookies, but due to the GDPR insanity making you have things included in policies, I always prefer to store the data in local storage.

So we shall assign different data-click="n" values to each link, where n is a unique value per link. When user clicks the link, we shall use local storage of format, {post-id} + {data-click attribute} and the value would be the number of link clicks.

$(document).ready(function() {
  var PostId = 2;
     var i = 0;  
$('.gotocls').each(function() {
  jQuery(this).attr('data-click', i);
  var ClickId = $(this).attr('data-click');
  var LocalKey = PostId + '+' + ClickId;
  if(localStorage.getItem(LocalKey)){
    if(localStorage.getItem(LocalKey) == '5'){
      $(this).hide();
    }
  }
  else{
    localStorage.setItem(LocalKey,0);
  }
   i++ 
});
});

You need to yourself put in the post id into the code. The above code runs on page load, and checks for buttons which have already had 5 clicks and hides them. If there exists a link that has never ever been clicked, it would create a new local storage item with value 0,




  $(document).ready(function(){
   $(".gotocls").click(function() {
       var PostId = 2;
      var ClickId = $(this).attr("data-click");
     var LocalKey = PostId + '+' + ClickId;
     count = localStorage.getItem(LocalKey);
     count ++;
       if(count > 4){
                localStorage.setItem(LocalKey, 5);
                $(this).hide();
       }
       else{
         localStorage.setItem(LocalKey, count);
       }
   });
  });

This code is responsible for handling the clicks. On each click it increments the value of clicks, and hides if the limit is reached. I havent tested the code, but you can try, I have high hopes for it. For Post Id, you can manually type in post id, or you can use it as Inline JS, and echo get_the_ID(); to get what you want.

Be the first to comment

Leave a Reply

Your email address will not be published.


*