Add Download Button and Counter Using WordPress Ajax

Add below code into functions.php

/* Enque script for ajax */
add_action('wp_enqueue_scripts', 'download_counter_enqueue');
function download_counter_enqueue() {
	wp_register_script('ajax-download-script', get_template_directory_uri() . '/js/dowload-counter.js', array('jquery'));
	wp_localize_script('ajax-download-script', 'ajax_download_object', array('ajaxurl' => admin_url('admin-ajax.php')));

/* Insert download counter using ajax */
function download_counter() {
    //update_post_meta(45, 'themes_downloads', 45);
    $wp_id = $_POST['wp_id'];
    $wp_downloaded = $_POST['wp_downloaded'];
    $wp_downloads_count = $wp_downloaded + 1;
    $wp_downloads = update_post_meta($wp_id, 'wp_downloads', $wp_downloads_count );
add_action( 'wp_ajax_download', 'download_counter' );
add_action( 'wp_ajax_nopriv_download', 'download_counter' );

Create new javascript file (dowload-counter.js)

/* WP themes Download counter */	
jQuery(document).ready(function($) {
            type: 'POST',
            dataType: 'json',
            url: ajax_download_object.ajaxurl,
            data: {
                    'action': 'download', //calls wp_ajax_nopriv_ajaxdownload
                    'wp_id': $('form#ajaxform #wp_id').val(),
                    'wp_downloaded': $('form#ajaxform #wp_downloaded').val(),
            success: function(){ }

Add below form and button code in sigle file (single.php)

$wp_downloaded = get_post_meta($post->ID, 'wp_downloads', true); ?>
<form id="ajaxform" action="ajaxform" method="post">
    <input type="hidden" name="wp_id" id="wp_id" value="<?php echo $post->ID; ?>" />
    <input type="hidden" name="wp_downloaded" id="wp_downloaded" value="<?php echo $wp_downloaded; ?>" />
    <input type="submit" name="submit" style="display:none;"/>
<a href="#">Download</a> <?php echo $wp_downloaded;

Tagged: ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: