Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

172
Views
Count how many times a user clicked to a button in WordPress Part2

I need to count how many times a user clicked a specific button, for example:

<div class="download" data-id="<?php echo $postID; ?>"><a href="<?php the_field('download_url'); ?>"><i class="fa fa-download fa-fw"></i> Download</a><?php the_field('download_count'); ?></div>

What´s best practice here? I think about to create a completely new database table and increment the value each time a user clicks on the button.

I am making two custom fields. [dounload_url: url] [download_cnt: 0]

jQuery

<script>
jQuery(function ($) {
    $('.download a').on("click", function(event) {
      event.preventDefault();
        var url_add = $(this).attr('href');
        var post_id = $('.download').attr('data-id');
        var ajaxurl = '';
    if(url_add && post_id) {
      $.ajax( {
        dataType: "url",
        url:ajaxurl,
        type: 'POST',
        data:{
          'action': 'countDL',
          'urladd':url_add,
          'postid':post_id
        }
      } )
    .done(function(){
    // go to the link they clicked
    window.location = $(this).attr('href');
    })
    .fail(function(xhr){
    console.log(xhr);
    })
  }
}); // jQuery End
</script>

functions.php

function countDL() {
  $postid = $_POST['postid'];
  $file = $_POST['urladd'];
  $num = get_field('download_cnt', $postid, true);
  if(!$num){
  $num=0;
  }
  $num++;
  update_field('download_cnt', $num, $postid);
  }
  
  add_action('wp_ajax_nopriv_countDL','countDL');
  add_action('wp_ajax_countDL','countDL');

Even if I click the link, the value of the custom field does not count up and I am in trouble.

Help me.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!