I've been developing a custom downloads counter for a website I'm attending right now and I had this idea of stop linking directly to the files and handle downloads via AJAX.
I've been able to make it work for loged in users but not for logged off users.
I create the links with custom code which results in something like
http:// mysite.com/?download=123 where the number is the post id, this is hooked with a jQuery.ajax() request which executes the hook
wp_ajax_bsf_download by calling the
action: 'bsf_download', which of course is registered by my plugin with
add_action( 'wp_ajax_bsf_download', 'bsf_handle_download');. The handler function retrieves a custom field in the post that contains the url to the file and adapts some stuff, like creating a downloadable zip file (for compatibility because some of the files are binaries not compatible with Safari) and then adds one to the downloads counter. Finally echoing a JSON string with the url to redirect the browser to (the zip file) and the number to be set on the single page where the downloads counter sits.
I have read the WP Docs and they only suggest the use of
add_action( 'wp_ajax_nopriv_bsf_download', 'bsf_handle_download'); which just doesn't work. I also did the
wp_enqueue_script() necessary calls
Can someone please point me in the right direction?