WordPress – CF7 – select fields – CPT

I recently had a challenge.
I had to create a form in WordPress which featured a select box.
Nothing fancy about that, except the owner wanted the select options to be based on the content of a custom post type.
This is proved to be quick trickey because I couldn’t find a CF7 (custom form seven) add on which allowed me to do it, so I had to create a routine to provide the functionality.

 

// this is the custom shortcode I add to the custom form.
wpcf7_add_shortcode( “committee_positions”,”page_handler” );

// this select will support muli-select options    –  so first, lets do the query to get the custome post data
function page_handler(){
$query = new WP_Query(array(
‘post_type’ => ‘committee_positions’,
‘post_status’ => ‘publish’,
‘posts_per_page’ => -1
));
// now lets create a string (called $html) to create the string of to make up field

$html=”<label>What positions are interested in?</label><br/>”;
$html.= “<select name=’comm_positions[]’ multiple=’multiple’ style=’width:58%’>”;
$html.= “<option value=’Undecided’ selected>Undecided</option>”;
while ($query->have_posts()) {
$query->the_post();
$html.= “<option value='”.get_the_title().”‘>”.get_the_title().”</option>”;
}
$html.= “</select>”;
$html.=”<br/><i>You may select more than one</i>”;
// reset the query & return the string  (called by the shortcode)

wp_reset_query();
return $html;
}
// handle the additional data (custom field) that is now available in the standard CF7 form

function filter_wpcf7_posted_data( $posted_data ) {
return $posted_data;
};
$posted_data = apply_filters( ‘wpcf7_posted_data’, $posted_data );
add_filter( ‘wpcf7_posted_data’, ‘filter_wpcf7_posted_data’, 10, 1 );
remove_filter( ‘wpcf7_posted_data’, ‘filter_wpcf7_posted_data’, 10, 1 );