Halloween Sale 15% off Ends in See the plans
PHP

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.

Don’t have WPIDE yet? Install it on your site

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

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.