I have been searching for a way to add a select field to the Contact form with custom data.
The goal is to have a form where someone can ask for information on an article by selecting the article with a select field.
What I did figure out is how to add the custom select field to the form with a filter
add_filter('wpcf7_form_tag_data_option', function($n, $options, $args){
// special data provider tag found ?
if (in_array('press_posts', $options)){
$data = array('Test1', 'Test2', 'Test3');
return $data;
}
// default - do not apply any changes within the options
return null;
}, 10, 3);
Now I only have to adde the following shortcode to the form
[select press_post include_blank id:press_select data:press_posts]
The only issue I am having with this is that this results in the following html.
<select name="press_post" class="wpcf7-form-control wpcf7-select" id="press_select">
<option value="">---</option>
<option value="Test1">Test1</option>
<option value="Test2">Test2</option>
<option value="Test3">Test3</option>
</select>
As you can see the Test1
value has a capital letter just like the others.
This is something I don't want and I would like to set the value myself.
I tried adding keys to the data array but that did not do anything.
Hope you guys can help me out.
**** EDIT ****
I currently got it working at a somewhat different way.
function dynamic_field_values($tag){
if ( $tag['name'] != 'press_post' )
return $tag;
$args = array (
'numberposts' => -1,
'post_type' => 'press_posts',
'orderby' => 'title',
'order' => 'ASC',
);
$custom_posts = get_posts($args);
if ( ! $custom_posts )
return $tag;
foreach ( $custom_posts as $custom_post ) {
$tag['raw_values'][] = $custom_post->post_title;
$tag['values'][] = $custom_post->ID;
$tag['labels'][] = $custom_post->post_title;
}
return $tag;
};
add_filter( 'wpcf7_form_tag', 'dynamic_field_values', 10, 2);
Currently just working out how I can get more data in the function so I can make this all dynamic.
If anyone knows how to do that it would be great if you could share that info with me :)
anyways how I want to call the field in Contact Form 7 is like this
[contact-form-7 id="9778" title="Press contact" number_of_posts="34" post_type="in_het_nieuws"]
Note the number_of_posts
and the post_type
parts.
dynamic_field_values
?