Download File after submission Contact Form 7 WordPress

I know how to redirect the form to another page after submitting a Contact form 7 build form in wordpress. So I can redirect it to a pdf file for example. ( it then opens in the browser)

But what I would like to have is a direct download upon submission. no redirect.

Read More

The code I use to redirect the form to the pdf file is:

on_sent_ok: "location = 'url to pdf file here';"

The perfect way it would be that the form will disappear and say
a Thank you notice on the place of the form and start the download of the PDF file

Related posts

2 comments

  1. You can force a pdf to be downloaded directly instead of being viewed on the server by adding this .htaccess file on the PDF directory.

    .htaccess – this will force PDF to be downloaded

    <FilesMatch ".(?i:pdf)$">
       ForceType application/octet-stream
       Header set Content-Disposition attachment
    </FilesMatch>
    

    or you you can try javascript ( untested )

    function force_download( file ) {
        pdf = window.open(file, '', 'left=100,screenX=100');
        pdf.document.execCommand('SaveAs', 'null', 'myfile.pdf');
        pdf.close();
     }
     on_sent_ok: "force_download('pdf_url_here');"
    
  2. Since the on_sent_ok has been deprecated, here is an example you could use for inspiration.
    I had the need to add a download CTA after the content of all case studies of a website, but “in exchange” of user’s data for:

    • display a CF7 form on your page, I had the same one on all case studies post type single which I hooked after the content
    • find a way to get the wanted PDF url for people to download, as for me all case studies have a different PDF, I simply added an ACF field, filtered on PDF only, which returns the file url
    • based on CF7 Dom events, choose the action you prefer to make the dowload happens, as I am not sending any confirmation email, I prefer working on the wpcf7submit event. Note that wpcf7submit event is fired only if the form has been validated

    So the code looks like this:

    <?php 
    // For simplicity, using an anonymous functions
    add_action( 'wp_print_footer_scripts', function () {
        // Check the wanted singular post type loading
        if ( is_admin() || ! is_singular( 'case-study' ) ) {
            return;
        }
    
        // Check if the ACF PDF field is not empty for use
        $pdf_link = get_field( 'pdf' );
        if ( empty( $pdf_link ) ) {
            return;
        }
    
        // Hook on the "wpcf7submit" CF7 Dom event to force the download
        printf( "<script>document.addEventListener( 'wpcf7submit', function( event ) { window.open('%s'); }, false );</script>", $pdf_link );
    } );
    

Comments are closed.