So I`m trying to generate a dynamic hidden text field that will have a random string of letters and numbers into Contact Form 7.
I have tried the following code
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 = 'rand_string';
$charsList = '1234567890abcdefghijklmnopqrstuvwxyz';
$randomString = '';
for ($i=4; $i < 10; $i++){
$randomString .= $charsList[rand(0, strlen($charsList))];
}
$finalCode = strtoupper($randomString);
$html = '<input type="hidden" name="'.$input_code_name.' "value=" '.$finalCode . ' " />';
return $html;
}
Based on this method https://www.wpguru.com.au/generate-dynamic-tag-contact-form-7/
However it does not seem to work for me, I added the code to functions and tried a bunch of editing to it with no definitive results.
Main idea is that I need a unique string of characters for each CF7 submission, all submissions are stored into Wordpress and also a copy of the data is sent to another DB.
Adding the shortcode [coupon_code] to mail template returns nothing and no data seems to get stored trough the field at all.
What you have should essentially work. I made some tweaks and optimized some of your code by removing some extraneous declarations and there were also extra spaces around the values.
add_action( 'wpcf7_init', 'custom_code_generator' );
function custom_code_generator() {
wpcf7_add_form_tag( 'coupon_code', 'custom_code_handler' );
}
function custom_code_handler() {
$characters = '1234567890abcdefghijklmnopqrstuvwxyz';
$random_string = '';
for ( $i = 4; $i < 10; $i++ ) {
$random_string .= $characters[ wp_rand( 0, strlen( $characters ) ) ];
}
return '<input type="hidden" name="rand_string" value="' . strtoupper( $random_string ) . '" />';
}