Solution:
Your question was almost correct. The set_properties()
needs to pass the whole array (in your case) $mailProp
.
/**
* Dynamically Change the recipient.
*
* @param object $contact_form The contact form 7 contact form object.
* @return void
*/
function cf7dynamicnotifications( $contact_form ) {
$submission = WPCF7_Submission::get_instance(); // Create instance of WPCF7_Submission class.
$posted_data = $submission->get_posted_data(); // Get all of the submitted form data.
// Make sure the field is filled in.
if ( isset( $posted_data['plz'] ) ) {
if ( '21079' === $posted_data['plz'] ) {
$recipient_email = 'office1@xyz.com';
} elseif ( '22085' === $posted_data['plz'] ) {
$recipient_email = 'office2@xyz.com';
} elseif ( '12345' === $posted_data['plz'] ) {
$recipient_email = 'office3@xyz.com';
} else {
$recipient_email = 'head-office@xyz.com';
}
// set the email address to recipient.
$mailProp = $contact_form->get_properties( 'mail' );
$mailProp['mail']['recipient'] = $recipient_email;
// update the form properties.
$contact_form->set_properties( array( 'mail' => $mailProp ) ); // Pass the whole array.
}
}