Contact Form 7: use hook created using wpcf7_before_send_mail for only one contact form by id

前端 未结 3 781
天涯浪人
天涯浪人 2020-12-09 18:40

I am working on a site with several forms created using Contact Form 7. For one of these forms, I am passing variables that I collected using a hidden input field in the fo

3条回答
  •  情歌与酒
    2020-12-09 19:40

    The methods for retrieving the form ID and submitted fields have changed in this plugin since 2015.

    To get the form ID, you should use this:

    $form_id = $contact_form->id();
    

    To get the submission data you should use this (instead of $_POST):

    $submission = WPCF7_Submission::get_instance();
    $posted_data = $submission->get_posted_data();
    

    To put it all together, your snippet would look like this:

    add_action( 'wpcf7_before_send_mail', 'wpcf7_add_text_to_mail_body' );
    function wpcf7_add_text_to_mail_body( $contact_form ) {
    
        //Get the form ID
        $form_id = $contact_form->id();
    
        //Do something specifically for form with the ID "123"
        if( $form_id == 123 ) {
            $submission = WPCF7_Submission::get_instance();
            $posted_data = $submission->get_posted_data();
            $values_list = $posted_data['valsitems'];
            $values_str = implode(", ", $values_list);
    
            // get mail property
            $mail = $contact_form->prop( 'mail' ); // returns array 
    
            // add content to email body
            $mail['body'] .= 'INDUSTRIES SELECTED';
            $mail['body'] .= $values_list;
    
            // set mail property with changed value(s)
            $contact_form->set_properties( array( 'mail' => $mail ) );
        }
    }
    

提交回复
热议问题