Fill a Contact Form 7 Drop-Down With Your Posts
Fills a Contact Form 7 select field with the titles of published posts, pages or a custom post type, so a services or products list stays in sync with your content.
Opens WPIDE on
Code
$wpide_cf7_select_field = 'menu-service'; // Name of the select tag to fill.
$wpide_cf7_select_type = 'page'; // Post type to list.
add_filter( 'wpcf7_form_tag', function ( $tag ) use ( $wpide_cf7_select_field, $wpide_cf7_select_type ) {
if ( empty( $tag->name ) || $tag->name !== $wpide_cf7_select_field || 'select' !== $tag->basetype ) {
return $tag;
}
$titles = get_transient( 'wpide_cf7_select_' . $wpide_cf7_select_type );
if ( false === $titles ) {
$ids = get_posts( array( 'post_type' => $wpide_cf7_select_type, 'post_status' => 'publish', 'numberposts' => 100, 'orderby' => 'title', 'order' => 'ASC', 'fields' => 'ids', 'no_found_rows' => true ) );
$titles = array_values( array_filter( array_map( function ( $id ) {
return wp_strip_all_tags( get_the_title( $id ) );
}, $ids ) ) );
set_transient( 'wpide_cf7_select_' . $wpide_cf7_select_type, $titles, HOUR_IN_SECONDS );
}
if ( $titles ) {
$tag->values = $titles;
$tag->raw_values = $titles;
$tag->labels = $titles;
}
return $tag;
} );
add_action( 'save_post_' . $wpide_cf7_select_type, function () use ( $wpide_cf7_select_type ) {
delete_transient( 'wpide_cf7_select_' . $wpide_cf7_select_type );
} );
Notes
Add an empty select tag such as [select* menu-service] to your form and set the field name and post type at the top; the list is cached for an hour and refreshed when a post of that type is saved.
How to add this snippet
- Install WPIDE on your WordPress site (it is free) and open Code Snippets.
- Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
- It is added inactive: review the code and settings, then switch it on.