Reputation: 909
I have a form on a WordPress site using Contact Form 7. I have a dropdown to choose a recipient but I don't want the email address listed there.
The recipients are listed from a custom post type and when the form is submitted I need to look up the email address based on the selection name. I've got the following code but it's not changing the recipient.
function wpcf7_before_send_mail_function( $contact_form, $abort, $submission ) {
$submission = WPCF7_Submission::get_instance();
$posted_data = $submission->get_posted_data();
if( $posted_data["your-recipient"] == 'General Enquiry' ) {
$recpage = get_page_by_title('James');
$recipient_email = $recpage->email_address;
} else {
$recpage = get_page_by_title($posted_data["your-recipient"]);
$recipient_email = $recpage->email_address;
}
$properties = $contact_form->get_properties();
$properties['mail']['recipient'] = $recipient_email;
$contact_form->set_properties($properties);
return $contact_form;
}
add_filter( 'wpcf7_before_send_mail', 'wpcf7_before_send_mail_function', 10, 3 );
Any idea why this doesn't alter the recipient address? Thanks.
Upvotes: 1
Views: 1618
Reputation: 5669
Your select data is posted as an array, since about 2020 with CF7. So you'll need to access the first value [0]
of that array to get the dropdown values. Also, as you commented, you need the third parameter of get_page_by_title
, and finally you don't need to use return
in your function, since it will execute your code and apply changes as needed to the objects. wpcf7_before_send_mail
is an action hook, not a filter.
function wpcf7_before_send_mail_function( $contact_form, $abort, $submission ) {
$posted_data = $submission->get_posted_data();
if ( 'General Enquiry' === $posted_data['your-recipient'][0] ) {
$recpage = get_page_by_title( 'James', OBJECT, 'your_CPT' );
$recipient_email = $recpage->email_address;
} else {
$recpage = get_page_by_title( $posted_data['your-recipient'][0], OBJECT, 'your_CPT' );
$recipient_email = $recpage->email_address;
}
$properties = $contact_form->get_properties();
$properties['mail']['recipient'] = $recipient_email;
$contact_form->set_properties( $properties );
// Do not return anything, since this is an action and not a filter.
}
add_filter( 'wpcf7_before_send_mail', 'wpcf7_before_send_mail_function', 10, 3 );
Upvotes: 1