Skip to content

Instantly share code, notes, and snippets.

@zainaali
Created November 5, 2021 11:17
Show Gist options
  • Save zainaali/d7b0354ddbc240129f8c6b8cc3b9549c to your computer and use it in GitHub Desktop.
Save zainaali/d7b0354ddbc240129f8c6b8cc3b9549c to your computer and use it in GitHub Desktop.
Dynamically populate a Contact Form 7 dropdown list form db and add custom validation
add this shortcode in contact from
[select upcoming-gigs data:gigs]
add this code in functions.php
<?php
add_filter('wpcf7_form_tag_data_option', function($n, $options, $args) {
global $wpdb;
$result = $wpdb->get_results("SELECT DATE_FORMAT(termin, '%d.%m.%Y') as termin FROM einweihungen where termin >= CURDATE() ORDER BY einweihungen.termin ASC;");
$optionsarr = array();
foreach ($result as $termin) {
$optionsarr[]=$termin->termin;
}
if (in_array('gigs', $options)){
$gigs =$optionsarr;
return $gigs;
}
return $n;
}, 10, 3);
add_filter( 'wpcf7_validate_select', 'wpharvest_custom_validation_select', 20, 2 );
/**
* Go through all the select fields
*/
function wpharvest_custom_validation_select( $result, $tag ) {
if ( 'upcoming-gigs' == $tag->name && empty( $_POST['upcoming-gigs'] )) {
$result->invalidate($tag, "This field is required.");
}
return $result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment