Post Contact Form 7 Messages to Slack
Sends a short summary of every Contact Form 7 submission to a Slack channel through an incoming webhook, so your team sees new leads right away.
Opens WPIDE on
Code
$wpide_cf7_slack_fields = array( 'your-name', 'your-email', 'your-subject', 'your-message' ); // Fields to include.
add_action( 'wpcf7_mail_sent', function ( $contact_form ) use ( $wpide_cf7_slack_fields ) {
$url = defined( 'WPIDE_SLACK_WEBHOOK_URL' ) ? (string) WPIDE_SLACK_WEBHOOK_URL : '';
$submission = WPCF7_Submission::get_instance();
if ( 0 !== strpos( $url, 'https://hooks.slack.com/' ) || ! $submission ) {
return;
}
$lines = array( sprintf( '*New message from "%s"*', $contact_form->title() ) );
foreach ( $wpide_cf7_slack_fields as $name ) {
$value = $submission->get_posted_data( $name );
if ( null !== $value && '' !== $value ) {
$value = is_array( $value ) ? implode( ', ', $value ) : (string) $value;
$lines[] = sprintf( '*%s:* %s', $name, wp_html_excerpt( str_replace( array( '<', '>', '&' ), array( '<', '>', '&' ), $value ), 500, '…' ) );
}
}
wp_safe_remote_post( $url, array(
'body' => wp_json_encode( array( 'text' => implode( "\n", $lines ) ) ),
'headers' => array( 'Content-Type' => 'application/json' ),
'timeout' => 5,
'blocking' => false,
) );
} );
Notes
Create an incoming webhook in Slack and define WPIDE_SLACK_WEBHOOK_URL in wp-config.php; the fields shown are listed at the top.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.