jrobinsonc
9/21/2016 - 6:25 PM

WordPress plugin - Contact Form 7 (wpcf7) snippets

WordPress plugin - Contact Form 7 (wpcf7) snippets

<?php

/**
 * Validate fields.
 * @see http://hookr.io/filters/wpcf7_validate_type/
 */
function wpcf7_validate( $result, $tag )
{
    $tag = new WPCF7_Shortcode( $tag );

    if ( 'email' === $tag->name ) {
        if ( filter_input(INPUT_POST, $tag->name, FILTER_VALIDATE_EMAIL) === false ) {
            $result->invalidate( $tag, "The email is not valid." );
        }
    }

    if ( 'zipcode' === $tag->name ) {
        if ( filter_input(INPUT_POST, $tag->name, FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'#^\d{5}$#']]) === false ) {
            $result->invalidate( $tag, "The Zip Code is not valid." );
        }
    }
    
    // Define: reCAPTCHA_KEY and reCAPTCHA_SECRET_KEY
    if ( 'captcha' == $tag->name ) {
        require_once 'utils/lib/recaptcha.php';
        $recaptcha = new reCaptcha(reCAPTCHA_KEY, reCAPTCHA_SECRET_KEY);

        $validate = $recaptcha->validateResponse();

        if (null === $validate) {
            $result->invalidate( $tag, "The captcha field is empty." );
        } else if (false === $validate) {
            $result->invalidate( $tag, "The captcha field is not valid." );
        }
    }

    if ( 'phone' === $tag->name ) {
        if ( filter_input(INPUT_POST, $tag->name, FILTER_VALIDATE_REGEXP, ['options'=>['regexp'=>'#^\(?\d{3}\)?[\s-]?\d{3}[\s-]?\d{4}$#']]) === false ) {
            $result->invalidate( $tag, "The phone is not valid." );
        }
    }

    return $result;
}

add_filter( 'wpcf7_validate_text*', 'wpcf7_validate', 20, 2 );
<?php

if (isset($_POST['_wpcf7'])) {
  $ok_msg = '{"mailSent":true,"into":"#'. $_POST['_wpcf7_unit_tag'] .'","captcha":null,"message":"%s"}';
  $error_msg = '{"mailSent":false,"into":"#'. $_POST['_wpcf7_unit_tag'] .'","captcha":null,"message":"%s","invalids":[]}';
  
  // exit(sprintf($ok_msg, 'Thank you for your message.'));
  // or
  // exit(sprintf($error_msg, 'There was an error, please try later.'));

}
<?php

/**
 * Modify the email before send.
 */
function wpcf7_before_send_mail($WPCF7_ContactForm) {

    $properties = $WPCF7_ContactForm->get_properties();
    
    $recipients_list = [
      1 => 'ABC1 <abc1@example.tld>',
      2 => 'ABC2 <abc2@example.tld>',
    ];
    
    // Update recipients:
    if (isset($recipients_list[$_POST['recipient']])) {
      $properties['mail']['recipient'] = $recipients_list[$_POST['recipient']];
    }

    $WPCF7_ContactForm->set_properties($properties);
}

add_filter( 'wpcf7_before_send_mail', 'wpcf7_before_send_mail' );