Contact Form 7 - Send Email To Post Author

Contact Form 7

What is Contact Form 7? This is an another plugin in Wordpress which manages multiple contact form. Additionally, one can customize the form based on their requirements.

One of our client recently asked us to send email to post author when someone (i.e. End User) post any enquiry of the respective post. Now, here I need to set dynamic email address of post author to send email to respective post author. How would you do it? 

A brainstorming task - searched on google for the day, and found one magical plugin Contact Form 7 Dynamic Text Extension which fulfill my requirements by customizing a little code.

By using Contact Form 7 Dynamic Text Extension plugin you can specify shortcode value into one of our form fields. Once the form submits, we can access the shortcode field value by the ordinary CF7 way, using [] brackets and the field identifier. With this method, we can easily pass dynamic data through our forms from our author’s meta.

Let me walk you through the implementation:

1. Make a simple email form with Contact Form 7:

Install Contact Form 7 and Contact Form 7 Dynamic Text Extension plugins and create a new contact form with the CF7 plugin. You can add any field to your form!

The only required one is a dynamic hidden type field. Add it and name it to custom-post-author-email-shortcode and at the Dynamic value field add the CUSTOM_POST_AUTHOR_EMAIL shortcode name!

Contact Form 7

Now click on Mail tab of CF7 form and fill up “To” field with your dynamic field: [custom-post-author-email-shortcode]. With this setting, we achieve that our contact form will send the message to our dynamically generated email address.

2. Register the custom shortcode to get the current author’s email

We just make a new shortcode for this job with the help of the WordPress Shortcode API!

You can place the following code snippet into a new plugin or your theme functions.php:

/**
 * Get the author's email address from the author meta infos.
 */
 
function custom_get_post_author_email($atts){
  $value = '';
  if(get_the_author_meta( 'user_email' )) {
    $value = get_the_author_meta( 'user_email' );
  }
  return $value;
}
add_shortcode(CUSTOM_POST_AUTHOR_EMAIL, custom_get_post_author_email);

With this simple short code, you get the post author email address and give it back as the shortcode value.

Hope this helped you all and save the vital time. Keep posting your feedback for us.