Fill a WPForms Drop-Down With Your Posts
Fills a WPForms drop-down with the titles of published posts, pages or a custom post type, both when the form is shown and when it is processed, so entries keep the chosen title.
Opens WPIDE on
Code
$wpide_wpf_post_choices = function ( $type ) {
$cache = 'wpide_wpf_choices_' . $type;
$choices = get_transient( $cache );
if ( false === $choices ) {
$choices = array();
$ids = get_posts( array( 'post_type' => $type, 'post_status' => 'publish', 'numberposts' => 200, 'orderby' => 'title', 'order' => 'ASC', 'fields' => 'ids', 'no_found_rows' => true ) );
foreach ( $ids as $i => $id ) {
$choices[ $i + 1 ] = array( 'label' => wp_strip_all_tags( get_the_title( $id ) ), 'value' => '', 'image' => '' );
}
set_transient( $cache, $choices, HOUR_IN_SECONDS );
}
return $choices;
};
$wpide_wpf_fill = function ( $form_data ) use ( $wpide_wpf_post_choices ) {
if ( empty( $form_data['fields'] ) || ! is_array( $form_data['fields'] ) ) {
return $form_data;
}
foreach ( $form_data['fields'] as $id => $field ) {
if ( 'select' === $field['type'] && ! empty( $field['css'] ) && preg_match( '/\bwpide-posts-([a-z0-9_-]+)\b/', $field['css'], $m ) && post_type_exists( $m[1] ) ) {
$form_data['fields'][ $id ]['choices'] = $wpide_wpf_post_choices( $m[1] );
}
}
return $form_data;
};
add_filter( 'wpforms_frontend_form_data', $wpide_wpf_fill );
add_filter( 'wpforms_process_before_form_data', $wpide_wpf_fill );
add_action( 'save_post', function ( $post_id, $post ) {
delete_transient( 'wpide_wpf_choices_' . $post->post_type );
}, 10, 2 );
Notes
Give the drop-down the CSS class wpide-posts-<post type> (for example wpide-posts-page) in the field's Advanced settings.
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.