Click Count on Download a File

i have website with woocommerce for digital download. I make all free for download, and this my code for download the file:

$downloads = $product-get_files();

foreach( $downloads as $key = $each_download ) {
  echo 'a href="'.$each_download["file"].'"Download/a';
}

My question, how to make click count in single product page if people click that link for download the file? I want to showing how many the file already downloaded... Can you tell me how make code for that? Thank you...

EDIT:

Hi, i found this code at https://wordpress.stackexchange.com/a/258902

?php
/* functions.php */
add_action( 'wp_ajax_link_check_click_counter', 'link_check_click_counter');
add_action( 'wp_ajax_nopriv_link_check_click_counter', 'link_check_click_counter' );
function link_check_click_counter() {

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


add_action( 'wp_footer', 'link_click' );
//add_action( 'wp_head', 'link_click' );
function link_click() {
    global $post;

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

        $( '#link_count a' ).on( 'click', function() {
            var href = $( this ).attr( "href" );
            var redirectWindow = window.open(href, '_blank');   
            $.post( ajax_options.ajaxurl, ajax_options, function() {
                redirectWindow.location;
            });
            return false;
        });
    });
    /script
?php
    }
}
?

But that code for external link, can i implement to my code? Can? How? Thankyou...

Topic woocommerce-offtopic count Wordpress

Category Web


Use this code..

$downloads = $product->get_files();
$product_id = $product->id;

foreach( $downloads as $key => $each_download ) {
    $query = "SELECT SUM( download_count ) AS count FROM {$wpdb->prefix}woocommerce_downloadable_product_permissions WHERE product_id = $product->id";
    $count = $wpdb->get_var( $query );
    if ( ! empty( $count ) ) {
      echo '<a href="'.$each_download["file"].'">Download ('.$count.')</a>';
    } else {
      echo '<a href="'.$each_download["file"].'">Download</a>';        
    }
}

Hope it works.. :)

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.