How to Dynamically Set the Recipient (To) Email Address in Contact Form 7

One question I get a lot is how to dynamically change the email recipient in Contact Form 7. It’s actually very easy, and with Contact Form 7 – Dynamic Text Extension (free download), you get a lot of flexibility.

The Basics

First, let’s start off with the basic mechanism: Create a tag that will contain the email address, and set that tag’s name as the email recipient. The simplest dynamic email address can be set with a basic text input. The contact form 7 tag would look like this:

[ text* recipient-email ]

Then, all we do is place the name tag in the Mail To: field, as such:

[recipient-email]

We end up with this:

Okay, that was easy. But this isn’t a very good idea. We don’t want just anyone to be able to change who the form is being sent to and then send out emails from our site.

Setting the Email Address Dynamically

Using CF7 DTX, we can dynamically set the email address for the form. The email address might be stored in a POST variable, for example, and we can retrieve it using the CF7_POST shortcode. Here we’ll walk through an example of setting the email address via a custom field (post meta data). This means the email address for the form will be determined by the post, so we can have a single CF7 contact form that is displayed on every post, each potentially aimed at a different recipient.

  1. Install Contact Form 7 and Contact Form 7 – Dynamic Text Extension
  2. Navigate to Contact > Edit
  3. Create or Edit a contact form
  4. Click Generate Tag and select Dynamic Text Field
  5. Set the Name to recipient-email
  6. Set the Dynamic Value to CF7_get_custom_field key='user_email'
  7. Click Make this field Uneditable – we don’t want users to change the email address!

At this point your Tag Generator should look like this:

  1. Copy the tag into the form. It’ll look like this: [dynamictext recipient-email uneditable "CF7_get_custom_field key='user_email'"]
  2. Copy the name tag [recipient-email] into the To: input.
  3. Save the form

The form is now set up to do what we want. The rest involves writing your posts.

  1. Create a post.
  2. Copy the CF7 Contact Form shortcode into the post. [ contact-form-7 id="963" title="Contact form 1" ]
  3. Set the custom field user_email to any email address.
  4. Your contact form will be sent to that email.
  5. Repeat the same process with the same form shortcode on a separate post with a new email address and the email will go to that address

Hiding the Email Address

That’s great, but we don’t really need to display the email to the user. In fact, we’d really rather not. Instead of a text field, we really just want a hidden input field. Luckily, that’s easy to do – just substitute a Dynamic Hidden Field for the Dynamic Text Field instead! The code simply changes like this:

[dynamichidden recipient-email "CF7_get_custom_field key='user_email'"]

Great! But one last thing: spam bots are going to grab this email address and spam the hell out of you. Damn. Let’s at least obfuscate the email a little to make it harder for them. It’s built in to the CF7_get_custom_field shortcode, so luckily it’s really easy. Just do this:

[dynamichidden recipient-email "CF7_get_custom_field key='user_email' obfuscate='on'"]

Awesome!! Now we’re good to go!

WordPress Mega Menu Plugin Announcement

Here’s a sneak peek of my new WordPress mega menu plugin, UberMenu, which will be released in the next few days.

It’s been in development for a month and a half, and I’ve added all sorts of great features that makes it super easy to create fantastic looking mega menus in WordPress. It even integrates directly with the WordPress 3 Menu Management System, so you don’t have to change any code to use it. It’ll work out of the box with any theme that supports the WordPress 3 Menu System (calls add_theme_support('menus') and has at least one registered menu area).

Here are a few of the features:

  • Works with WordPress 3 Menu System
  • 10 Preset Styles included
  • Great Control Panel options for customization and configuration
  • Create your own styles easily with the Style Generator
  • Add descriptions and images right from the WordPress Menus panel
  • Supports both horizontal and vertical menu styles
  • Includes both Fade and Slide effects
  • Choose from click or hover submenu triggers
  • UberMenu is fully widgetized, so adding non-link content to your mega menu is as easy as dragging and dropping a widget
  • If widgets can’t take care of your needs, UberMenu also supports shortcode content, so the menu content is fully customizable

And more! Check out the UberMenu Demo Site to find out more, and look for UberMenu to be released in the next couple of days.

How to Create a Dynamic WordPress Contact Form

Say you want to allow users to contact you, and you want to provide some context for their inquiry. For example, you might want to know where they came from before they sent you their message. You can achieve this with a combination of Contact Form 7 and my plugin, Contact Form 7 Dynamic Text Extension.

This tutorial assumes you have already installed the Contact Form 7 and Dynamic Text Extension plugins.

The Contact Page

First thing you’ll need is a Contact Page. Create a new WordPress page and call it something exciting like “Contact”.

The Contact Form

Next, you’ll need to create a Contact Form. Navigate to Contact > Edit in your Control Panel. You’ll get a default form with your basic fields: Name, Email, Subject, Message.

To provide some context to the form, we’ll add a new field. We’ll call it “Context”, but you could call it something more specific (like “Product” or “URL” or whatever). To do this, we add a Dynamic Text Field that will pull the context from the GET variables in the URL (we’ll set those up in the next step). The GET variable will be called “context”.

You can use the WPCF7 Tag Generator to create the Dynamic Text field.

Namecontact-form-context
idcontact-form-context
Make this field uneditablechecked
Keeps the user from changing this on you
Dynamic ValueCF7_GET key=”context”
This tells the form to grab the context GET variable from the URL.

The tag ends up looking like this:

[dynamictext contact-form-context id:contact-form-context uneditable "CF7_GET key='context'"]

Take the shortcode and place it in the Form Text with a label like “Context”

<p>Context <br/>
[dynamictext contact-form-context id:contact-form-context uneditable "CF7_GET key='context'" ]
</p>

Save your form. Copy the shortcode it generates for you and place it in the text of the Contact page you created, for example (surround this with square brackets []):

contact-form 1 "Contact form 1" 

Linking to the Contact Page

Now all that’s left is to pass the context variable to the Contact Form. Say you have a bunch of posts (or pages) and when a user contacts you, you want to know what page they clicked “contact” on.

For each page you want this on, you just create a link to the Contact page with the proper variable set in the URL. Use the following format:

<?php 

echo '<a href="http://mysite.com/contact?context='. urlencode("My Page About Aardvarks").'" >Contact Us</a>'; 

?>

Where contact is the slug of your contact page, context is the key of the variable you set the contact form to pick up in the Dynamic Value contact form tag field (i.e. CF7_GET key=’context’), and

more generally, to always pass the title of the post:

<?php

global $post;
echo '<a href="http://mysite.com/contact?context='.urlencode(get_the_title($post->ID)) .'">Contact Us</a>';

?>

Now when a user clicks the link, they’ll be taken to your contact form with the context field pre-populated. Awesome!

Here’s an example, context set to “how-to-create-a-dynamic-wordpress-contact-form”:
Contact Me!

An Alternate Solution: Contact Form on each page

If you’d rather put the contact form on each page, you can do that too! You only need to create one form, but for your dynamic text field you just use the shortcode CF7_get_post_var key='title' instead of the CF7_GET shortcode.

Want to set the URL instead of the post title? Just use the shortcode CF7_URL instead of CF7_get_post_var key=title.

Contact Form 7 – Dynamic Text Extension Released

Sorry, comments are closed due to ridiculous amounts of sp*m. Please use the WordPress.org forums for support. Thanks!

I’ve just released my first WordPress Plugin: Contact Form 7 – Dynamic Text Extension.

I’ve used the Contact Form 7 Plugin several times on my own sites and on client sites. It’s an excellent, highly flexible plugin. But I recently needed to populate the form dynamically, and found this functionality was not build in to the plugin.

I found other people with similar issues. Several possible solutions are suggested in this thread, Contact Form 7 Input Fields Values as PHP Get-Viarables, but they are all hacks and involve changing the Contact Form 7 code, which is bad for a variety of reasons. The new plugin provides a better solution, hooking into Contact Form 7’s API and adding a new input type: Dynamic Text. This input type takes a shortcode-style input that is evaluated at run time, so it can be completely dynamic.

For example, say you have a GET parameter in the URL that you want to use to populate the contact form. You just set the Dynamic Text field up with the included shortcode and GET key, and the value will automatically be populated. Cool! Better yet, the plugin will work with any shortcode that returns a valid text string, so you can easily extend the plugin just by writing your own shortcodes. Awesome!

Anyway, the plugin is now available through WordPress.org. Let me know if it helps you out!

Download the Plugin Donate

Internet Explorer: Operation Aborted & Bing Maps

Recently, I had a client who wanted a map of Israel on their site. I started out using Google Maps as I always do for this process, but the Israel map contains no details when embedded (even though it’s fully detailed – cities, roads, etc – in the Google Maps application). The reason for this is unclear, though some have speculated it’s due to licensing issues with the Google Maps API. So, I decided to use Bing Maps instead.

Embedding a Bing Map is not nearly as straightforward as embedding Google Maps. Luckily for me, there’s a great WordPress plugin called Bing Maps for WordPress which provides a simple-to-use shortcode. I installed the plugin and had the map working very quickly.

[bingMap location="Israel"]

Simple. However, a few days later I noticed that when I loaded the page in IE7 during testing, the following message popped up, and the page, which had previously loaded almost entirely, redirects to a “Page Cannot be Displayed” screen (now that’s dumb):

Internet Explorer cannot open the Internet Site
Operation Aborted

After swearing at Internet Explorer for a few minutes as usual, I proceeded to find that this has to do with adding DOM elements to the body element… incorrectly. Of course, it works just fine in Firefox, Chrome, and every other browser.

Getting past the irony of Microsoft’s Bing Maps nuking Microsoft’s Internet Explorer when embedded, the solution is fairly simple. The basic idea is to defer the loading of the map till the DOM is ready. The Defer a script until the page has loaded solution is detailed as such:

if (window.attachEvent) {
	window.attachEvent("onload", GetMap);
} else {
	window.addEventListener("load", GetMap, false);
}

To accomplish this with the Bing Maps for WordPress plugin, I edited the plugin’s content.php file. As the site already used jQuery, I just added a jQuery(document).ready() around the function call. The edits look like this:

//line 331
$string .= '<script type="text/javascript">jQuery(document).ready(
   function(){ 
      map = new VEMap('bingMapsForWordpress'.$this->mapCount.'');
      map.SetCredentials("'.$this->apiKey.'");
      map.LoadMap(new VELatLong('.$this->lat.', '.$this->long.', 0, VEAltitudeMode.RelativeToGround), '.$this->atts['zoomDynamic'].', VEMapStyle.'.$this->maptypesDynamic[strtolower($this->atts['maptype'])].', false, VEMapMode.Mode2D, true, 1);
      var layer = new VEShapeLayer();';

//line 398
$string .= '}); </script>';

And that’s it! Now it works like a charm. If only we could rename Internet Explorer “Operation Aborted”…

Photo by jeffwilcox

TED Talks: Where good ideas come from

Here’s a really cool talk by Steven Johnson on how great ideas come into existence. He describes how ideas form, not as “eureka!” moments as they are often described, but rather through networks of thought and collaboration. He poses that Darwin’s “lightbulb” moment of discovery with the theory of natural selection is better described as the moment that his ideas came into sharp focus, rather than the moment at which the ideas were formed, and that in fact he had all the components of his theory laid out in his detailed notes months beforehand.

He also gives a great tie-in in telling the story of how GPS was born from a collaborative snowball-effect of hunches. Entertaining and informative – definitely worth a look! And it provides some general principles that those with startup ideas can apply to their own pursuits.

You can read a related New York Times article here: People and Places That Innovate, or buy his book on Amazon here Where Good Ideas Come From: The Natural History of Innovation.