I’m trying to find a way to override or filter the output of the Contact Form 7 response boxes which are shown when a form error or success message is shown.

As default, Contact Form 7 outputs this HTML when a form sends successfully:

<div class="wpcf7-response-output wpcf7-display-none wpcf7-mail-sent-ok" style="display: block;" role="alert">
    Thank you for subscribing!
</div>

Effectively, I want to change the output HTML of the response to be a Bootstrap dismissable alert like so:

<div class="wpcf7-response-output wpcf7-display-none alert alert-success" role="alert">
    Thank you for subscribing!
</div>

I’ve tried scouring the Contact Form 7 documentation and looked through the plugins source code to find the filter that I think I need, but I can’t get the response HTML output to change. This is the code that I’ve tried:

function filter_wpcf7_response_output( $output ){
    // Replace Success CSS Class
    $output = str_replace( ' wpcf7-mail-sent-ok', ' alert alert-success', $output );
    return $output; 
}
add_filter( 'wpcf7_form_response_output', 'filter_wpcf7_response_output', 10, 1 );

But it doesn’t appear to change the output at all… Any help would be greatly appreciated!

1
1

After taking a deeper look in to this, I realised that the responses that are displayed are produced via the Contact Form 7 AJAX.

So, following the Contact Form 7 documentation on DOM Events, I was able to get this working how I wanted with the following JS code:

/* Validation Events for changing response CSS classes */
document.addEventListener( 'wpcf7invalid', function( event ) {
    $('.wpcf7-response-output').addClass('alert alert-danger');
}, false );
document.addEventListener( 'wpcf7spam', function( event ) {
    $('.wpcf7-response-output').addClass('alert alert-warning');
}, false );
document.addEventListener( 'wpcf7mailfailed', function( event ) {
    $('.wpcf7-response-output').addClass('alert alert-warning');
}, false );
document.addEventListener( 'wpcf7mailsent', function( event ) {
    $('.wpcf7-response-output').addClass('alert alert-success');
}, false );

Leave a Reply

Your email address will not be published. Required fields are marked *