Archive for November, 2010

Auto Populate Contact Form 7 Input Fields with URL Parameter

I've just finished a WordPress development project which required fields in contact forms to be auto-populated with values based on the page from which the form page was called. In this case I was using the Contact Form 7 plugin. It's fairly simple to set default input field values with Contact Form 7 but assigning values dynamically based on context proved to be a bit more of a challenge. Needless to say though, a bit of hacking and an hour so on Google yielded a satisfactory result.

The site allows users to browse from a selection of ski chalets and submit a reservation enquiry. First of all I had to work out how to pass the name of the chalet being enquired about to the contact form page. I found this post which told me how to do this using a bit of extra code in the theme's functions.php file as follows:


// chalet name for enquiry form
function parameter_queryvars( $qvars ) {
    $qvars[] = 'chalet';
    return $qvars;
}
add_filter('query_vars', 'parameter_queryvars' );

function echo_chalet() {
    global $wp_query;
        if (isset($wp_query->query_vars['chalet']))
        {
            print $wp_query->query_vars['chalet'];
        }
}

This sets up a new WordPress query variable called "chalet", allowing the chalet enquiry form page to be called as follows:

http://domainname.com/chalet-enquiry/?chalet=chaletname

Next, how to insert the value of "chaletname" into the relevant field on the form? Some unsuccessful hacking of Contact Form 7's text.php module followed by further Googling led me to theĀ Contact Form 7 Dynamic Text Extension plugin which is designed specifically to add this capability to Contact Form 7. The plugin creates a new field type tag for the form called "dynamictext", which allowed me to create an input field in the form to accept the "chaletname" variable passed to the page as follows:


[dynamictext enquiry-chalet "CF7_GET key='chalet'"]

It works a treat and even better allowed me to leave the Contact Form 7 core code unhacked.

View a demo here

Thanks to WordPress Warrior for the functions.php extension and Sevenspark for the plugin.