How do I change the recipient in functions.php in WordPress Contact Form 7?

Viewed 296

I'm trying to replace the email recipient in the Contacnt Form 7 plugin with the value from the Advanced Custom Fields plugin, because I have a dynamic recipient in each record. I found a function on the internet, but it doesn't work for me, the form returns a sending error.

function wpcf7_before_send_mail_function( $contact_form, $abort, $submission ) {
            global $post;
            $dynamic_email = get_field('form_email',$post->ID); // get your email address...
        
            $properties = $contact_form->get_properties();
            $properties['mail']['recipient'] = $dynamic_email;
            $contact_form->set_properties($properties);
        
            return $contact_form;
        
        }
add_filter( 'wpcf7_before_send_mail', 'wpcf7_before_send_mail_function', 10, 3 );

Maybe there's a simpler function that works, or is there something I'm doing wrong?

1 Answers

There's a few things with your function that need to be updated.

  1. It's an action, not a filter add_action so you don't have to return anything.
  2. The post_id can't be retrieved the way you have it. Use the property from the $submission class.
function wpcf7_before_send_mail_function( $contact_form, $abort, $submission ) {
    // Container Post ID from CF7 $submission class
    // $submission->get_meta('container_post_id')
    $dynamic_email = get_field('form_email', $submission->get_meta('container_post_id'));

    $properties = $contact_form->get_properties();
    $properties['mail']['recipient'] = $dynamic_email;
    $contact_form->set_properties($properties);
    // You don't have to return $contact_form, you're using the set_properties function.
    //return $contact_form;
}
add_action( 'wpcf7_before_send_mail', 'wpcf7_before_send_mail_function', 10, 3 );
Related