First, let’s add a custom function to track clicks and increment a meta field:
function track_file_download($post_id, $share_file_url) {
// Increment download count
$current_count = get_post_meta($post_id, 'file_download_count', true);
$new_count = intval($current_count) + 1;
update_post_meta($post_id, 'file_download_count', $new_count);
}
Create a custom shortcode or template function to display the share file with tracking:
function display_shareable_file($post_id = null) {
// If no post ID is provided, use the current post
if (!$post_id) {
$post_id = get_the_ID();
}
// Get the share file URL
$share_file_url = get_post_meta($post_id, 'share_file', true);
if ($share_file_url) {
// Generate a unique tracking link
$tracking_url = add_query_arg([
'download' => base64_encode($post_id),
'file' => base64_encode($share_file_url)
], home_url());
// Output the link with download count
$download_count = get_post_meta($post_id, 'file_download_count', true) ?: 0;
return sprintf(
'<a href="%s" class="file-download-link">Download File (%d downloads)</a>',
esc_url($tracking_url),
intval($download_count)
);
}
return '';
}
add_shortcode('share_file', 'display_shareable_file');
Add a handler to process the download tracking:
function handle_file_download_tracking() {
if (isset($_GET['download']) && isset($_GET['file'])) {
$post_id = base64_decode($_GET['download']);
$file_url = base64_decode($_GET['file']);
// Validate the post ID and file URL
if ($post_id && $file_url) {
// Track the download
track_file_download($post_id, $file_url);
// Redirect to the actual file
wp_redirect($file_url);
exit;
}
}
}
add_action('init', 'handle_file_download_tracking');
Usage examples:
echo display_shareable_file(); // For current post
echo display_shareable_file($specific_post_id); // For a specific post