Dynamic Select List in Contact Form 7

Contact Form 7 is an ultimate tool when it comes to forms in WordPress. Populate a select dropdown field with dynamic data is also possible in it with just a few lines.

Making a dynamic dropdown field in your form can be useful. If you manage your solutions in a custom post type, maybe you want to display an area with them in your request form. You can also show anything you want; it will depend on your site/project.

Create a Dynamic Dropdown in WPCF7

To make a populated field, we can use the wpcf7_form_tag filter to catch a field name and attach our data.

function pine_dynamic_select_field_values ( $scanned_tag, $replace ) {  
  
    if ( $scanned_tag['name'] != 'solutions' )  
        return $scanned_tag;

    $rows = get_posts(
    	array ( 
	     'post_type' => 'solutions',  
	     'numberposts' => -1,  
	     'orderby' => 'title',  
	     'order' => 'ASC' 
        )
    );  
  
    if ( ! $rows )  
        return $scanned_tag;

    foreach ( $rows as $row ) {  
        $scanned_tag['raw_values'][] = $row->post_title . '|' . $row->post_title;
    }

    $pipes = new WPCF7_Pipes($scanned_tag['raw_values']);

    $scanned_tag['values'] = $pipes->collect_befores();
    $scanned_tag['pipes'] = $pipes;
  
    return $scanned_tag;  
}  

add_filter( 'wpcf7_form_tag', 'pine_dynamic_select_field_values', 10, 2);  

Let’s see what this code do:

  1. First, we catch the wpcf7_form_tag filter.
  2. Then we check if the tag name is “solutions” to hook correctly.
  3. After this, we query our content; this can be anything you wish. Here we used get_posts to access a custom post type. We also check if we have values.
  4. We populate the WPCF7 object with the correct values; this means the raw_values, values, and pipes.
You can place this code into a plugin our in your theme’s functions.php.

As you see, we used the WPCF7_Pipes helper to process the raw_values which we attached to the values field. The pipes in Contact Form 7 means that you can hide data from the user with a pipe syntax like this: Adam | [email protected]. You can display data in the editor in this format, and only the first part (before the pipe) will be displayed and the second serves as a value when you send an email. So in this way, we can hide/filter out the sensitive data from the front-end.