You could save your AJAX pain and go about this in a different way by placing a hidden field within your form in PHP.
Method 1, with the aid of a plugin
I generally use the Contact Form 7 Dynamic Text Extension plugin as an easy route to creating custom CF7 tags, which still needs a little coding. You could also go the extra distance and just code your own CF7 tags, but I haven’t tried that yet, but I might as an edit to this answer.
With this plugin in place you can put tags into your CF7 form like this:
[dynamichidden custom-reg-code “CF7_custom_reg_code”]
And in the email pane of CF7’s admin page you’d insert [custom-reg-code].
To get it working, just make yourself a matching shortcode to generate your string:
function generateRandomString($length = 10) {
return substr(str_shuffle(str_repeat($x='0123456789', ceil($length/strlen($x)) )),1,$length);
}
function wpse306816_CF7_custom_reg_code() {
return date("Ymd") . generateRandomString();
}
add_shortcode('CF7_custom_reg_code', 'wpse306816_CF7_custom_reg_code');
Hat-tip to https://stackoverflow.com/a/13212994/6347850 for the random number generation.
Now you will have a hidden field in your form made up of the current date and a random number that you can use in your form’s sent email or save in Flamingo just like any other CF7 field.
Method 2, without the aid of a plugin
And a little research has shown that it’s even easier to just write your own CF7 tag and not bother with the plugin.
To create a CF7 tag [serial]
, you register it using wpcf7_add_form_tag()
on the wpcf7_init
action hook, passing the name of the tag and the name of a callback function to handle it:
add_action( 'wpcf7_init', 'wpse306816_CF7_add_custom_tag' );
function wpse306816_CF7_add_custom_tag() {
wpcf7_add_form_tag(
'serial',
'wpse306816_CF7_handle_custom_tag' );
}
And for your case, the callback simply needs to return the serial string value:
function generateRandomString($length = 10) {
return substr(str_shuffle(str_repeat($x='0123456789', ceil($length/strlen($x)) )),1,$length);
}
function wpse306816_CF7_handle_custom_tag( $tag ) {
return date("Ymd") . generateRandomString();
}