Download pdf file after submitting the Contact Form 7
some time ago i have created a form using Contact Form 7 on my client’s site. where user fill the given field then after submit the form a PDF file starts download automatically. I have only one file to download, so it should be very simple and I don’t want to install any plugin to achieve this functionality. So I found a simple solution for this.
<?php add_action( 'wp_footer', 'add_download_pdf_file' ); function add_download_pdf_file() { $pdf_url = 'https://www.wpwebguru.com/wp-content/uploads/2021/04/Sample.pdf'; $contactform_id = (int) 1039; $filename = 'WpWebGuru'; ?> <script> document.addEventListener( 'wpcf7mailsent', function( event ) { if ( <?php echo $contactform_id;?> == event.detail.contactFormId ) { jQuery('body').append('<a id="cf7fd-attachment-link" href="<?php echo $pdf_url; ?>" target="_blank" download="<?php echo $filename; ?>"></a>'); jQuery('#cf7fd-attachment-link')[0].click(); setTimeout(function() { jQuery('#cf7fd-attachment-link').remove(); },2000); } }, false ); </script> <?php } ?>
if you want to add pdf file on multiple form then you can use this code
<?php add_action( 'wp_footer', 'add_download_pdf_file' ); function add_download_pdf_file() { $data = array ( array( "id"=>"331", "url"=>"https://www.wpwebguru.com/wp-content/uploads/2021/04/Sample-1.pdf", "name"=>"File 1" ), array( "id"=>"332", "url"=>"https://www.wpwebguru.com/wp-content/uploads/2021/04/Sample-2.pdf", "name"=>"File 2" ), array( "id"=>"333", "url"=>"https://www.wpwebguru.com/wp-content/uploads/2021/04/Sample-3.pdf", "name"=>"File 3" ), ); ?> <script> <?php $index=1; foreach ( $data as $p ) { ?> document.addEventListener( 'wpcf7mailsent', function( event ) { if ( <?php echo $p['id'];?> == event.detail.contactFormId ) { jQuery('body').append('<a id="cf7fd-attachment-link<?php echo $p['id'];?><?php echo $index;?>" href="<?php echo $p['url'];?>" download="<?php echo $p['name'];?>"></a>'); jQuery('#cf7fd-attachment-link<?php echo $p['id'];?><?php echo $index;?>')[0].click(); setTimeout(function() { jQuery('#cf7fd-attachment-link<?php echo $p['id'];?><?php echo $index;?>').remove(); },2000); } }, false ); <?php $index=$index+1; } ?> </script> <?php } ?>
And that’s it! I hope you have find this blog useful! Happy coding!
4 replies on “How To Download pdf file after submitting the Contact Form 7”
Thank you!
Hi, appreciate your sharing and I got recommendation from Blue Sky team.
The first PHP is exactly what I am looking for. Shame I am not a code specialist so would you help and tell me where to place the code paragraph in my Bluehost dashboard please? Thanks a bunch first.
just put that code in your themes functions.php at the bottom
The first PHP worked perfectly. Thank you.
Only thing is it doesn’t work on iPhone? Any ideas appreciated. Thank you