Useful codes for Contact Form 7 Plugin.

Redirect user to ‘thank you’ page on submission

Below the contact form under “additional settings” add the following code:

on_sent_ok: "location = 'http://www.website.com.au'"

Make validation tip disappear on hover

Add code into header.php just before

<script type="text/javascript">
jQuery(document).ready(function($) {
    // clear cf7 error msg on mouseover
    $(".wpcf7-form-control-wrap").mouseover(function(){
        $obj = $("span.wpcf7-not-valid-tip",this);
                $obj.css('display','none');
    });
});
</script>

Adds placeholder for select fields instead of “select option”

function my_wpcf7_form_elements($html) {
    function ov3rfly_replace_include_blank($name, $text, &$html) {
        $matches = false;
        preg_match('/<select name="' . $name . '"[^>]*>(.*)<\/select>/iU', $html, $matches);
        if ($matches) {
            $select = str_replace('<option value="">---</option>', '<option value="">' . $text . '</option>', $matches[0]);
            $html = preg_replace('/<select name="' . $name . '"[^>]*>(.*)<\/select>/iU', $select, $html);
        }
    }
    ov3rfly_replace_include_blank('state', 'Select State*', $html);
    return $html;
}
add_filter('wpcf7_form_elements', 'my_wpcf7_form_elements');

Direct successful form submission to a Thank you page

<script type="text/javascript">
var pathname = window.location.origin;

document.addEventListener( 'wpcf7mailsent', function( event ) {
    if ( '5' == event.detail.contactFormId ) { // Sends sumissions on Subscribe Form
    location = pathname+'/thank-you/';
    } else if ( '157' == event.detail.contactFormId ) { // Sends submissions on Turn In Form
        location = pathname+'/thank-you/';
    } else { // Sends submissions on all unaccounted for forms to the third thank you page
        location = pathname +'/thank-you/';
    }
}, false );
</script>

Form validation before submitting

<script>
// CONTACT FORM & VALIDATION    
// Name can't be blank
$('#reqname').on('change', function() {
$(this).removeClass('wpcf7-not-valid');
});

$('#reqphone').on('change', function() {
var inputVal = $(this).val();
var re = /^\(?\+?([0-9]{1,4})?\)?[-\. ]?(\d{10})$/;
if (re.test(inputVal)) {
$(this).removeClass('wpcf7-not-valid');
}
});

$('#reqemail').on('change', function() {
var inputVal = $(this).val();
var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
if (re.test(inputVal)) {
$(this).removeClass('wpcf7-not-valid');
}
});
</script>

Contact me.

I would love to hear from you, send me a message using the form below.

    ×