Another Random Media & Technology Post

Adding Variables to Contact Form 7

Adding Variables to Contact Form 7

I recently wanted to add the shopping cart contents of a WP Ultra simple Paypal Cart into Contact Form 7 so that the information from the cart was sent with the form when it was submitted.  Adding Variables to Contact Form 7 actually isn’t as difficult as I thought!

First, I had to name the Contact 7 form for identification. If I was handcoding a form, I’d just add: name ='my_form'. But as the Contact 7 documentation states, you only need to include html_name='my_form' in the Contact 7 shortcode.

Then, adding a small piece of javascript will automatically grab the product information and quantity and add it to the specified field of the Contact 7 form:

function confirmProducts() {
var product = document.getElementsByClassName("cartLink");
var quantity = document.getElementsByClassName("iquantity");
var n = product.length;
for (var i = 0; i < n; i++){
var products = [product[i].innerHTML];
var quantities = quantity[i].value;
var allProducts = quantities + " " + products;
var productList = allProducts.replace(/(<([^>]+)>)/ig," ");
document.my_form.yourorder.value += productList + "\r\n";

This code grabs all of the order information from the Shopping cart and places it into the Contact 7 form named “my_form” in the field called “yourorder” (a field created in the Contact 7 Form) as highlighted above. For me, the trickiest part was just figuring out the right operator ‘+=’ to add all of the products. (It’s always the little things that trip me up!)

Anyway, I just added the above code to the WordPress page with the ‘cart’ and Contact 7 shortcodes. WP Ultra simple Paypal cart needs to be set up with “3 Step cart form URL” which is at the bottom of the plugin’s settings page. Contact Form 7 needs to be configured as described in WPUSPC:

1. Go to edit your form,
2. Scroll down and go to “Additional Settings” text area,
3. Paste => on_sent_ok: “location = ‘’;” (replace by your own URL) ,
4. And create page if not existing, plus past [show_wp_shopping_cart] shortcode

EDIT: Contact Form 7 is deprecating the on_sent_ok method. See this post.

Finally, at the bottom of the form/cart checkout page, add the following code in order to activate the earlier piece of code when the page loads.

if(window.attachEvent) {
 window.attachEvent('onload', confirmProducts);
} else {
 if(window.onload) {
 var curronload = window.onload;
 var newonload = function(evt) {
 curronload(evt);        curronload(evt);
 window.onload = newonload;
 } else {
 window.onload = confirmProducts;

Although the above code is specifically designed for WP Ultra Simple PayPal Cart, it can be modified slightly for adding variables to Contact Form 7 using just about any other source of data.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.