Insipration

Block Heap

Web Developer's Blog

Set Email Recipients by Form Input With Contact Form 7 (CF7)

Example:

The snippet below will be added to the functions.php file in the main directory of your WordPress theme.

Our code starts by ensuring that we’re using the right form since most sites have more than one. I like to use $wpcf7->id but you could easily use something like $wpcf7->title.


function contact_form_to($wpcf7) { // open the function

	if ($wpcf7->id !== 784) {
		// return without altering if not form 784
		return $wpcf7;
	}

Next, we get submission data and mail objects.


	$submission = WPCF7_Submission::get_instance();
	$mail = $wpcf7->prop('mail');

In this next part, we’re capturing data from a radio button input that is not set to accept multiple values. Your configuration will differ depending on the types of inputs that you want to capture.

We use a few WordPress core functions to keep our data tidy.

  • esc_html – Escaping for HTML blocks.
  • wptexturize – Replaces common plain text characters into formatted entities
  • wp_unslash – Remove slashes from a string or array of strings.

	// use key name of your field
	$radio_input = $submission->get_posted_data('residential');

	$property_address = esc_html($radio_input[0]);
	$property_address = wptexturize($radio_input[0]);
	$property_address = wp_unslash(trim($radio_input[0]));

At this point, it’s time to decide where to send emails. Our solution sends maintenance emails for certain addresses to individual staff members. Your solution may differ.


	$filter = array(
		'123 Automattic Court',
		'456 Silicon Valley',
		'789 Some other adress',
	);
	if (in_array($property_address, $filter)) {
		$mail['recipient'] = $mail['recipient'].', [email protected], [email protected]';
	}

Finally, we update the existing mail variable with the new recipients and close the function.

Notice the final line that runs the function when the wpcf7_before_send_mail action fires.


	$wpcf7->set_properties(array("mail" => $mail));
	return $wpcf7;

} // close the function
add_action( 'wpcf7_before_send_mail', 'contact_form_to' );

Download the source code here.
 
 

SIDEBAR HERE