Change CF7 Form values dynamically Change CF7 Form values dynamically wordpress wordpress

Change CF7 Form values dynamically


You can use my code to do this. Some explanations for your code:

1) Since id $cf7->id property is no longer accessible. Use id() method instead $cf7->id().

2) No need use & for callback $cf7 and $submission. Use for this return.

add_action("wpcf7_before_send_mail", "wpcf7_do_something");function wpcf7_do_something($WPCF7_ContactForm){    if (224 == $WPCF7_ContactForm->id()) {        //Get current form        $wpcf7      = WPCF7_ContactForm::get_current();        // get current SUBMISSION instance        $submission = WPCF7_Submission::get_instance();        // Ok go forward        if ($submission) {            // get submission data            $data = $submission->get_posted_data();            // nothing's here... do nothing...            if (empty($data))                return;            // extract posted data for example to get name and change it            $name         = isset($data['your-name']) ? $data['your-name'] : "";            // do some replacements in the cf7 email body            $mail         = $wpcf7->prop('mail');            // Find/replace the "[your-name]" tag as defined in your CF7 email body            // and add changes name            $mail['body'] = str_replace('[your-name]', $name . '-tester', $mail['body']);            // Save the email body            $wpcf7->set_properties(array(                "mail" => $mail            ));            // return current cf7 instance            return $wpcf7;        }    }}

That is all, we are changed some tags, and send email with modified tag ;-)


As I needed to modify form receivers based on ACF fields, here is a copy and paste solution which is based on @Brotheryura code.

It allows you to modify the recipient of the email dynamically without having any hidden fields in the front end. Simpy put it in your templates functions.php and replace the $recipient = ... part with your own function or code to get the new receiver.

add_action("wpcf7_before_send_mail", "wpcf7_change_recipient");function wpcf7_change_recipient($WPCF7_ContactForm){    $wpcf7      = WPCF7_ContactForm::get_current();    $submission = WPCF7_Submission::get_instance();    //some little magic to get the referers ID    $recipient  = get_field('mail', url_to_postid(wp_get_referer()));    if (!empty($recipient))    {        if ($submission)        {            $data = $submission->get_posted_data();            // nothing's here... do nothing...            if (empty($data))                return;            // do some replacements in the cf7 email body            $mail              = $wpcf7->prop('mail');            $mail['recipient'] = $recipient;            // Save the email body            $wpcf7->set_properties(array(                "mail" => $mail            ));            // return current cf7 instance            return $wpcf7;        }    }}