Send Contact Form 7 Messages to the Post Author
When a Contact Form 7 form is placed on a post, listing or profile page, the message goes to that post's author instead of the site admin.
Opens WPIDE on
Code
$wpide_cf7_author_post_types = array( 'post' ); // Post types whose author receives the message.
add_filter( 'wpcf7_mail_components', function ( $components, $contact_form = null, $mail = null ) use ( $wpide_cf7_author_post_types ) {
$submission = class_exists( 'WPCF7_Submission' ) ? WPCF7_Submission::get_instance() : null;
if ( ! $submission || ( $mail && method_exists( $mail, 'name' ) && 'mail' !== $mail->name() ) ) {
return $components;
}
$post = get_post( (int) $submission->get_meta( 'container_post_id' ) );
if ( ! $post || ! in_array( $post->post_type, $wpide_cf7_author_post_types, true ) ) {
return $components;
}
$author = get_userdata( (int) $post->post_author );
if ( $author && is_email( $author->user_email ) ) {
$components['recipient'] = $author->user_email;
}
return $components;
}, 10, 3 );
Notes
Limit it to certain post types with the list at the top; on other pages the form's own recipient is used.
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.