Stuart Pontins
Stuart Pontins

Reputation: 285

Contact form 7 - dynamic recipient email

I'm trying to grab the recipient email dynamically from custom fields and use a string replace to modify the contact form 7 recipient email. The contact form is sending but it doesn't seem to be changing the recipient email as I'm not getting the emails.

<?php
function wpcf7_dynamic_email_field( $args ) {

    $dynamic_email = '';
    $submission = WPCF7_Submission::get_instance();
    $unit_tag = $submission->get_meta( 'wpcf7-f3936-p3933-o1' );

    // get the post ID from the unit tag
    if ( $unit_tag && preg_match( '/^wpcf7-f(\d+)-p(\d+)-o(\d+)$/', $unit_tag, $matches ) ) {
        $post_id = absint( $matches[2] );
        $dynamic_email = get_post_meta( $post_id, 'email', true );
    }
    if ( $dynamic_email ) {
        $args['recipient'] = str_replace('[email protected]', $dynamic_email, $args['recipient']);
    }

    return $args;
}

add_filter( 'wpcf7_mail_components', 'wpcf7_dynamic_email_field' );
?>

I'm running CF7 4.5.1 and PHP 5.3 am I missing something here?

Upvotes: 7

Views: 8198

Answers (2)

Aurovrata
Aurovrata

Reputation: 2289

It's not very clear what you are trying to do with the unit tag, however, here is an alternative way to solve your problem,

function wpcf7_dynamic_email_field( $args ) {
    //create a hidden field with your post-id
    $dynamic_email = '';
    if(isset($_POST['post-id'])){
      $post_id = $_POST['post-id'];
      $dynamic_email = get_post_meta( $post_id, 'email', true );
    }
    if ( $dynamic_email ) {
        $args['recipient'] = str_replace('[email protected]', $dynamic_email, $args['recipient']);
    }

    return $args;
}

add_filter( 'wpcf7_mail_components', 'wpcf7_dynamic_email_field' );

in order to get the post-id populated you can either do using javacript on the client side, or you could get it pre-loaded at form loading time using the CF7 Dynamic Text extension (see a tutorial here).

Upvotes: 3

lukeseager
lukeseager

Reputation: 2615

To send an email to a dynamic recipient wince WPCF7 5.2, this is how I do it:

function wpcf7_before_send_mail_function( $contact_form, $abort, $submission ) {

  $dynamic_email = '[email protected]'; // 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 );

Upvotes: 8

Related Questions