How to display custom post type as a drop-down field in Contact Form 7
Hello, my first post here. Recently I had a client who wanted to show custom post type items as a choice in a Contact Form 7 form. If you think about it it makes a perfect sense.
An example: you have a custom post type Services and on the Contact page visitor can select service from a dropdown field. We will solve this with a custom form tag, functionality built into Contact Form 7. Here is the complete code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
add_action('wpcf7_init', 'custom_add_form_tag_customlist'); function custom_add_form_tag_customlist() { wpcf7_add_form_tag(array('customlist', 'customlist*'), 'custom_customlist_form_tag_handler', true); } function custom_customlist_form_tag_handler($tag) { $tag = new WPCF7_FormTag($tag); if (empty($tag -> name)) { return ''; } $customlist = ''; $query = new WP_Query(array('post_type' => 'CUSTOM POST TYPE HERE', 'post_status' => 'publish', 'posts_per_page' => -1, 'orderby' => 'title', 'order' => 'ASC', )); while ($query -> have_posts()) { $query -> the_post(); $post_title = get_the_title(); $customlist. = sprintf('%2$s', esc_html($post_title), esc_html($post_title)); } wp_reset_query(); $customlist = sprintf('%3$s', $tag -> name, $tag -> name.'-options', $customlist); return $customlist; } |
References:
https://contactform7.com/2015/01/10/adding-a-custom-form-tag
https://stackoverflow.com/questions/27867260/contact-form-7-and-custom-post-type
Leave a Reply