How to generate dynamic tag and input values for Contact Form 7

Contact Form 7 is one of my go to plugin, and I choose it most of time for my project. It’s easy to customise in terms of look and feel, extendable and maintained quiet well. For me as WordPress Developer, this plugin works as charm. Generating a hidden field with dynamic value in Contact Form […]

dynamic tag and input contact form 7

Contact Form 7 is one of my go to plugin, and I choose it most of time for my project.

It’s easy to customise in terms of look and feel, extendable and maintained quiet well. For me as WordPress Developer, this plugin works as charm.

Generating a hidden field with dynamic value in Contact Form 7

Here is a block of code I am sharing, which creates a random coupon code and adds as hidden field.

This code generates the [coupon_code] that can be used inside form generator and email replies, inside text or html format.

Add the block of code below in your functions.php file to see the magic.

<?php 

add_action('wpcf7_init', 'custom_code_generator');

function custom_code_generator(){
	wpcf7_add_form_tag('coupon_code', 'custom_code_handler');
}

function custom_code_handler($tag){
	$input_code_name = 'your_input';

	$charsList = '1234567890abcdefghijklmnopqrstuvwxyz';

	$randomString = '';

	//change the value of i to meet your requirements
	for ($i=0; $i < 10; $i++){
		$randomString .= $charsList[rand(0, strlen($charsList))];
	}

	$finalCode = strtoupper($randomString);

	//create html and return

	$html = '<input type="hidden" name="'.$input_code_name.' "value=" '.$finalCode . ' " />';

	return $html;

}

About Author

Robin Thebe

Digital Strategist based in Sydney.

I am multi disciplined web developer based in Sydney focusing around WordPress web design, wordpress development, SEO, SEM and Email Marketing.