This code will need the user to submit the form successfully before downloading the file. The browser inspection will not reveal the file’s URL before the form submission.
Add the below code to the template files. Please note that the ACF field with the field download and type file is used with the return value as file URL.
<div class="download-side-section"> <h3 class="download-title">Download File</h3> <a href="javascript:void(0)" class="btn btn-primary trigger download-core-btn" data-toggle="modal" data-target="#download" data-download="<?php the_title(); ?>">Download <i class="fas fa-long-arrow-alt-right"></i></a> <!-- modal for download and contact --> <div class="modal fade" id="download" role="dialog" > <div class="modal-dialog" > <div class="modal-content"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> <div class="title"> <h3 class="download-form-title">Download File?</h3> <p>Please provide your Name and Email Address to download file.</p> </div> <?php echo do_shortcode('[contact-form-7 id="817" title="Download Form"]'); ?> </div> </div> </div> </div> <script> document.addEventListener( 'wpcf7mailsent', function( event ) { if ( '817' == event.detail.contactFormId ) { var text = document.getElementById("posttitle").value; var filename = "<?php the_field('file'); ?>"; download(filename, text); var sp1 = document.createElement('a'); sp1.innerHTML = 'Download File <i class="fas fa-download"></i>'; sp1.setAttribute('href', filename); sp1.setAttribute('download', text); sp1.setAttribute('class','btn download-btn'); var sp2 = document.querySelector('.wpcf7-response-output'); var parentDiv = sp2.parentNode; parentDiv.insertBefore(sp1, sp2); sp2.style.display='none'; } }, false ); function insertAfter(referenceNode, newNode) { referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling); } function download(file, text) { //creating an invisible element var element = document.createElement('a'); element.setAttribute('href', file); element.setAttribute('download', text); // Above code is equivalent to // <a href="path of file" download="file name"> document.body.appendChild(element); //onClick property element.click(); document.body.removeChild(element); } </script>
Note: Bootstrap model is used for the form popup and contact form 7 is used for the user download form.