Aşağıdaki HTML kodu tıklanan buton, bir onclick event vererek count işlemini sunucu bazlı yapacağız.
<a href="/indirilecek dosya-url" onclick="mydownloadcount(this)" data-post-id="<?php echo intval(get_the_ID()); ?>">dosyayı indir</a>Javascript ile veriyi alıyor ve yolluyoruz
function mydownloadcount(item){
var post_id = $(item).attr("data-post-id "); // JQuery bağımlılığı ile kodladım. Temanızda illa vardır sanıyorum.
var ajaxUrl = "/wp-admin/admin-ajax.php"; // burayı kendinize göre düzenleyin. custom post type'larda 404 basabilir. en sağlıklısı php ile bu veriyi geçmek ama, şu an buradan yazmam zor olur.
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var icerik = xhr.response;
if (xhr.status >= 200 && xhr.status < 300) {
if(icerik == "yes"){
console.log("başarıyla count verisi yolladım!");
}
}
};
xhr.open("POST", ajaxUrl, true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send( "action=letscountdown&post_id="+post_id +"");
}Fonksiyon dosyasında JS'den gelen veriyi işliyoruz
// kayıt etme ve sanitize fonksiyonu
function letscountdown(){
$post_id = intval($_POST["post_id"];
if(is_numeric($post_id) && $post_id > 0)
{
$prev_post_count = get_post_meta($post_id, "download_count", true); // yeni indirmeden önceki post_count'u aldık.
$new_post_count = $prev_post_count + 1;
$insert = update_post_meta($post_id, "download_count", $new_post_count);
if($insert){
echo "yes";
}
}
}
// download count'u aldıran fonksiyon
function get_post_download_count((int)$post_id){
return get_post_meta($post_id, "download_count", true);
}Ardından ise indirme sayısını post sayfasında göstermek için aşağıdaki PHP kodunu çalıştırabiliriz.echo intval(get_post_download_count(get_the_ID()));Genel olarak en temiz mantık budur.