Questions & Answers

how to (programmatically) change values of cf7 fields before the form is displayed to the user

I'm no expert programmer but I wouldn't want to use an entire plugin to simply put a single value from $_POST into a "readonly" field, to be displayed to the user. I could use a regular form, but I want to use CF7 because the form contains other data and I'm afraid I'll cause security problems if I dont build the whole form as CF7-secure form.
(I've been subscribed to 'stackoverflow' for a long time but this is my first question, inescapably stupid I guess).

I found a way to do this with a CF7 hook but... only if the field is hidden (ie using 'wpcf7_form_hidden_fields' filter), but this only works on hidden fields. Do I have forcely to use javascript?

Answers(1) :

it seems that the problem is not interesting or that no one can give an answer. However I finally found a solution. The idea is to directly modify the 'form' field of postmeta and 'postcontent' which describe the cf7 form. Reading those fields and using a regular expression to find the right place to insert my desired value. The solution is not of a general order (but with a little work it could even become one). Applies to fields that accept a single value, and you must give an initial value - of course in quotes as expected by cf7. That's how:

$my_new_value = 'my desired value';
$id_my_cf7form = xxxx; // id of th cf7 form (from shortcode)
$name_my_cf7field = 'mio-nome-campo';
// I get the content of the meta 'form' field of the cf7 postmeta that I want to modify 
$meta_my_cf7form = html_entity_decode(get_post_meta( $id_my_cf7form, '_form', true ));  // questa è una stringa

// I build the new content with the new title value. the regular expression looks for the first 
// occurrence of the quotation mark after the field name, the next one and then replaces the contained value
$meta_my_cf7form = preg_replace("/($name_my_cf7field\s*\b[a-zA-Z0-9]+\b\s*)(\"[^\"]*\")/", "$1\"$my_new_value\"", $meta_my_cf7form);

// and finally I update the content of the postmeta
update_post_meta( $id_my_cf7form, '_form', $meta_my_cf7form );

/* I don't know if strictly necessary, but for safety and completeness
I also update the content of the 'post_content' field of the cf7 post I want to edit */

$my_post_array = get_post( $id_my_cf7form, 'ARRAY_A' ); // this is an associative array 

// I get the post-content of the cf7 post
$my_post_content = html_entity_decode($my_post_array['post_content']);

// I build the new content with the new value
$$my_post_array['post_content']  = preg_replace("/($name_my_cf7field\s*\b[a-zA-Z0-9]+\b\s*)(\"[^\"]*\")/", "$1\"$my_new_value\"", $my_post_content);

// and I update the content of the cf7 post
wp_update_post( $my_post_array );