mardi 24 février 2015

wordpress count link clicks by ip address


I am building wordpress web site, which will have an option to download zip file from certain custom post type. By clicking on download button, user automatically starts with downloading zip file.



<a id="countable_link" href="#">download</a>


My goal is to display the number of downloads next to the very same button. So far everything is working well, except the fact that I am able to trigger counter infinity number of times.


Instead of it, i would like that counter can be executed only once by the unique user. I am assuming that this has to do something with users ip address, but my knowledge of PHP, SQL and ajax is extremely poor.


Here is the script that i have found: (it has also been posted here)



<?php

if ( is_admin() ) add_action( 'wp_ajax_nopriv_link_click_counter', 'link_click_counter' );
function link_click_counter() {

if ( isset( $_POST['nonce'] ) && isset( $_POST['post_id'] ) && wp_verify_nonce( $_POST['nonce'], 'link_click_counter_' . $_POST['post_id'] ) ) {
$count = get_post_meta( $_POST['post_id'], 'link_click_counter', true );
update_post_meta( $_POST['post_id'], 'link_click_counter', ( $count === '' ? 1 : $count + 1 ) );
}
exit();
}


add_action( 'wp_head', 'link_click_head' );
function link_click_head() {
global $post;

if( isset( $post->ID ) ) {
?>
<script type="text/javascript" >
jQuery(function ($) {
var ajax_options = {
action: 'link_click_counter',
nonce: '<?php echo wp_create_nonce( 'link_click_counter_' . $post->ID ); ?>',
ajaxurl: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
post_id: '<?php echo $post->ID; ?>'
};

$( '#countable_link' ).on( 'click ', function() {
var self = $( this );
$.post( ajax_options.ajaxurl, ajax_options, function() {
window.location.href = self.attr( "href" );
});
return false;
});
});
</script>
<?php
}
}
?>


When I put this snippet into my functions.php file, it generates custom field value with exact number of clicks. Would be great if these numbers are more realistic. For example, if it displays value of 350 , people would really like to know that 350 different users downloaded the content.


I am grateful for any solution beside using additional plugins. If somehow can be incorporated into this snippet, it will just end up circle perfect for me.


Thanks,





Aucun commentaire:

Enregistrer un commentaire