Skip to content

Instantly share code, notes, and snippets.

@MogulChris
Last active January 27, 2019 21:22
Show Gist options
  • Save MogulChris/f62f87f26ba4eea7d0cf915f47634db6 to your computer and use it in GitHub Desktop.
Save MogulChris/f62f87f26ba4eea7d0cf915f47634db6 to your computer and use it in GitHub Desktop.
Contact Form 7 custom field values
<?php
/*
This goes in your functions.php or similar. It works the same for selects and radio buttons
In this example, we will provide dynamic values for a select named 'example-field1'
CF7 form tag: [select example-field1]
*/
function mytheme_cf7_dynamic_values($tag){
//make sure this is a field we want to modify - add more field names to the array to handle multiple fields
if ( !in_array($tag['name'], array('example-field1')) )
return $tag;
switch($tag['name']){
case 'example-field1':
//your custom value code goes here, eg getting titles of a custom post type named 'centre'
$centres = get_posts(array(
'post_type' => 'centre',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC'
));
if(empty($centres)) return $tag;
foreach($centres as $centre){
$tag['raw_values'][] = $centre->post_title;
$tag['values'][] = $centre->post_title;
$tag['labels'][] = $centre->post_title;
}
//print_r($tag);
break;
}//switch
return $tag;
}//mytheme_cf7_dynamic_values()
add_filter( 'wpcf7_form_tag', 'mytheme_cf7_dynamic_values', 10, 2);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment