如何统计下载次数
wptutor
2025-01-21
3 Views
// Function to handle downloads and count
function handle_file_download() {
if (!isset($_GET['file_id']) || !isset($_GET['post_id'])) {
return;
}
$attachment_id = intval($_GET['file_id']);
$post_id = intval($_GET['post_id']);
$file_url = wp_get_attachment_url($attachment_id);
if (!$file_url) {
wp_die('File not found');
}
// Increment download count
$current_count = carbon_get_post_meta($post_id, 'dp_download_count') ?: 0;
$new_count = (int)$current_count + 1;
carbon_set_post_meta($post_id, 'dp_download_count', $new_count);
// Redirect to actual file
wp_redirect($file_url);
exit;
}
add_action('init', 'handle_file_download');
下载按钮的设置
<div class="purchase-button">
<?php
$post_id = get_the_ID();
$attachment_id = carbon_get_post_meta(get_the_ID(),'dp_download_file')[0]['file']; ?>
<a href="<?php echo home_url('?file_id=' . $attachment_id . '&post_id=' . $post_id); ?>" class="btn btn--lg btn-primary">下载</a>
</div>