Advanced Custom Fields (ACF) provides out of the box much-needed functionality for adding custom fields to the WordPress core. It is the most popular custom fields plugin for WordPress at the time of writing this post, and has been for years.
The ACF provides a file field form. This allows us to easily create a custom field to allow users to upload files, then we attach it to a specific custom post-type, and finally display the file URL within the post-type it was attached to, easily. Very easily. At Zedafrica we have used this workflow to build complex document repositories and even user-submitted forms. Very easily.
The challenge though comes in, when there is a need for event tracking (and there should be), and even more, being able to track the number of downloads the ACF files get, and display this number as a counter.
To track advanced custom fields (ACF) file field downloads and display them as a counter, you can use the following steps:
// Get the download count field value $download_count = get_field('download_count'); // Get the file field value $file = get_field('file'); // Display the download count and file download link echo '<div class="download-counter">'; echo '<span class="counter">' . $download_count . '</span>'; echo '<a href="' . $file['url'] . '" class="download-link">Download</a>'; echo '</div>';
Here is an example of custom code that you can use to track and update the download count field value each time the file is downloaded:
function update_download_count() { // Get the current post ID $post_id = get_the_ID(); // Get the download count field value $download_count = get_field('download_count', $post_id); // Increment the download count field value by 1 $download_count++; // Update the download count field value update_field('download_count', $download_count, $post_id); } add_action('wp_footer', 'update_download_count');
<script> jQuery(document).ready(function($) { // Select the download link $('.download-link').click(function() { // Trigger the update_download_count action $(document).trigger('update_download_count'); }); }); </script>
This code will increment the download count field value by 1 each time the download link is clicked. You can adjust the code as needed to fit your specific requirements.