Skip to content

Instantly share code, notes, and snippets.

@campusboy87
Last active April 9, 2024 12:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save campusboy87/8c4819fff7a51f96787da37773f67023 to your computer and use it in GitHub Desktop.
Save campusboy87/8c4819fff7a51f96787da37773f67023 to your computer and use it in GitHub Desktop.
Allows you to use html in cf7 notifications + replaces a successfully submitted form with a success message
<?php
( new CF7_Notification_Shortcodes() )->hooks();
/**
* Allows you to use shortcodes in the CF7 form settings in the "Notifications when submitting a form" tab.
*/
class CF7_Notification_Shortcodes {
private array $shortcodes = [];
public function hooks(): void {
add_filter( 'wpcf7_submission_result', [ $this, 'special_mail_tags' ] );
add_action( 'wp_enqueue_scripts', [ $this, 'attach_assets' ] );
}
public function attach_assets() {
wp_enqueue_script(
'wpcf7submit_notification_with_html_tags',
// IMPORTANT: Replace the path to the file js to the one where you will have it
get_template_directory_uri() . '/js/wpcf7submit_notification_with_html_tags.js',
[ 'contact-form-7' ]
);
}
public function special_mail_tags( $result ) {
if ( empty( $result['message'] ) ) {
return $result;
}
$this->register_shortcode_link();
$result['message'] = do_shortcode( $result['message'] );
$this->remove_shorcodes();
return $result;
}
private function register_shortcode_link(): void {
$shortcode = 'link';
add_shortcode( $shortcode, static function ( $atts ) {
return sprintf(
'<a href="%s" target="_blank">%s</a>',
esc_url( $atts['url'] ),
esc_html( $atts['text'] )
);
} );
$this->shortcodes[] = $shortcode;
}
public function remove_shorcodes(): void {
foreach ( $this->shortcodes as $shortcode ) {
remove_shortcode( $shortcode );
}
}
}
document.addEventListener('wpcf7submit', function (event) {
try {
// Api
let formCssId = event.detail.apiResponse.into.substring(1);
let message = event.detail.apiResponse.message;
let status = event.detail.apiResponse.status;
// Dom
let doc = new DOMParser().parseFromString(message, 'text/html');
let htmlMessage = doc.body.innerHTML;
let containerForm = document.getElementById(formCssId);
let form = containerForm.querySelector('form');
let containerMessage = form.querySelector('.wpcf7-response-output');
setTimeout(function () {
containerMessage.innerHTML = htmlMessage;
// If you need to replace the form with a notification, otherwise delete it
if ('mail_sent' === status) {
form.innerHTML = containerMessage.outerHTML;
}
}, 100);
} catch (error) {
console.log(error);
}
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment