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.