How To Use Dynamic jQuery Form Fields in WPCF7 Email

How To Use Dynamic JQuery Form Fields In WPCF7 Email Banner

Recently, I was working on a project that required a very specific, feature-packed form that was able to store values in a database and email multiple recipients. I’ve been a big fan of the WordPress plugin Contact Form 7 for many years and although it isn’t saturated with out-of-the-box features, it’s very developer-friendly and flexible. So, I set off to use my trusty WPCF7 plugin and everything was great until I realized that I’m creating dynamic form fields from a custom post type filtered by multiple taxonomies while using jQuery to inject them into the form, but – and here’s the kicker – I needed to use those dynamic form fields inside of the email.

Uh oh…

For about a week, I struggled trying to get this working and I kept running into dead ends. I Googled until my fingers bled, but this was one of those cases where I was either the first person on the planet to try something like this or nobody had written any tutorials on this subject. I thought maybe I could use the wpcf7_special_mail_fields filter and just grab the $_POST data inside it. NOPE! I then thought, well what if I could use AJAX to store the data as a transient in the database and then pull it back out later. Maybe, but that seemed like more effort than was necessary. Finally, I stumbled across an article written by Tom Elliott at Web Dev Door that details how to execute a function before the Contact Form 7 submit action.

Although this particular article didn’t exactly meet all of my needs, it gave me an idea: what if I used the wpcf7_before_send_mail action in WPCF7 to write the $_POST data to a text file, and then I could use the “wpcf7_special_mail_fields” to make my own custom shortcode to fetch the contents of the text file EXCELSIOR! … or something like that.

I created two functions: store_equipment() and get_equipment() These two functions serve to store the $_POST data into the text file and retrieve the contents of the text file for use in the email. I then use the add_action call to fire the store_equipment() function after form submission and before sending the email. Then I use the add_filter call to create a custom shortcode to use within the email itself that will pull the contents out of the file.

function store_equipment( $cf7 ) {
// Reset the $output variable so as not to confuse anything
$output = '';
// Define $post as global
 global $post;
 // Loop through all of the $_POST data
 foreach ( $_POST as $key => $value ) {
 // We only want non-empty values
 if ( !empty( $value ) ) {
 // Check if the $value contains "qty-" at the beginning
 if ( strpos( $key, "qty-" ) !== FALSE ) {
 // Strip the key down slug
 $equipment_slug = str_replace( 'qty-', '', $key );
 // Define the args for the query
 $args = array(
 'name' => $equipment_slug,
 'post_type' => 'equipment',
 'post_status'=> 'publish',
 'showposts' => 1,
 'caller_get_posts' => 1
 );
 // Look up the equipment based on the args
 $posts = query_posts( $args );
 // Get the pretty looking name
 $post_name = $posts[0]->post_title;
 // Set the output to dump into the file
 $output .= ''."\n";
 $output .= ''.$post_name.''."\n";
 $output .= ''.$value.''."\n";
 $output .= ''."\n";
 }
 }
 }
file_put_contents( 'equipment-list.txt', $output );
 }
 add_action( 'wpcf7_before_send_mail', 'store_equipment' );
function get_equipment( $output, $name, $html ) {
 if ( '_get_equipment' == $name ) {
 // Get the file contents
 $output = file_get_contents( 'equipment-list.txt' );
 }
 return $output;
 }
 add_filter( 'wpcf7_special_mail_tags', 'get_equipment', 20, 3 );

It’s as simple as that. The first function takes the $_POST data, loops through it, formats it into a slug so we can query the database for the “pretty” equipment name ($posts[0]->post_title), puts it into the table markup that I’ll be using in the email form later, and returns the output. One thing to note, you won’t be able to echo any of this data to the screen during this function as WPCF7 is using AJAX. Instead, you could set the variable $output = print_r( $_POST, true ); if you wanted to dump the array contents so that you can see what all is in there.

After dumping the contents into the text file, you can get the contents of the file by utilizing file_get_contents and attaching it to the wpcf7_special_mail_tags filter.

Conclusion

This was a very intense problem for me to solve and proved to be quite the burden. I tried reaching out on some of the support channels and even contacted a few other agencies to see if anyone could help me. Unfortunately, all of them turned me down as no one could meet my deadline objectives. I even thought about scrapping this entire methodology and just hand-coding a form and handler and using WordPress’s built-in mailer. I’m glad I didn’t go that route.

Some of you may say, “Why did you use CF7 in the first place? Gravity Forms or Formidable would’ve been better. Perhaps, but I’m not comfortable with either of those plugins and taking the time to learn either of them would have been a much bigger burden and would have taken considerably more time than trying to make my solution work. I know a lot about Contact Form 7 and I like the flexibility it offers. For this project, I simply didn’t know where to hook my code in to make it work.

You might also ask why I even needed to use dynamic jQuery form fields in WPCF7 rather than using the typical static method. The simple answer is: automation. I’m trying to automate everything possible for the client to make it easier on them. My client doesn’t know how to build forms, nor do they care. They don’t know how to edit markup, nor will they ever want to. They want to add equipment items in the future themselves, but that poses a huge challenge like this because how do you throw fields into an email when you have no idea what they are or how they’re named? This way, I’m able to provide the client with the flexibility of being able to add those custom post types themselves, name them whatever they want, and this script will still pull the correct values in blindly and automatically add them to the email.

I’m not saying that my way is the best way, but it definitely works. How would you have done this differently? Is there any flaws you see in my code that could be improved upon? Let me know in the comments below!

Tags: , , ,

Article written by Mike Smith

7Articles Mike Smith on LinkedIn | Email Mike Smith

Mike is the Electronic Media Director and Site Administrator for Frontera Marketing Group. Since building his first website in 1996 using animated GIFs of flaming skulls on GeoCities, he's graduated to advanced HTML5/CSS3 techniques and is well versed in front-end design and back-end development with PHP/MySQL. When not building websites, Mike likes spending time with his family, playing video games, writing articles about technology, photography, and building custom computers.

Trackbacks are closed, but you can post a comment.

One Comment


  1. silverplugins217

    contact form 7 dynamic field is best plugin for used in hidden values and add any value in the shortcode in the hidden field.

    October 4th, 2022 at 3:27 am Reply

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>