Contact Form 7 – Dynamically populate dropdown list

Populate Select List

We can achieve the result with some really simple PHP, using the wpcf7_form_tag_data_option action hook. I failed to find any good documentation about this powerful feature. That’s why I wrote this post.

add_filter( 'wpcf7_form_tag_data_option', 'dynamic_select_list', 10, 3);
function dynamic_select_list($n, $options, $args) {
	if (in_array('division', $options)){
	  $division= array(
		"MAY 07 - NEW ORLEANS, LA",
		"MAY 09 - AUSTIN, TX",
		"MAY 12 - HOUSTON, TX"
	  );
	  return $division;
	}
	return $n;
}

Used

[select divisionname data:division]

Populate Select List With Taxonomy

The following is a more up to date way to dynamically populate the built-in select with options and could easily be extended to support more.

add_filter( 'wpcf7_form_tag', 'dynamic_select_taxonomy', 10 );
function dynamic_select_taxonomy( $tag ) {

    // Only run on select lists
    if( 'select' !== $tag['type'] && ('select*' !== $tag['type']) ) {
        return $tag;
    } else if ( empty( $tag['options'] ) ) {
        return $tag;
    }

    $term_args = array();

    // Loop thorugh options to look for our custom options
    foreach( $tag['options'] as $option ) {

        $matches = explode( ':', $option );

        if( ! empty( $matches ) ) {

            switch( $matches[0] ) {

                case 'taxonomy':
                    $term_args['taxonomy'] = $matches[1];
                    break;

                case 'parent':
                    $term_args['parent'] = intval( $matches[1] );
                    break;

            }
        }

    }

    // Ensure we have a term arguments to work with
    if( empty( $term_args ) ) {
        return $tag;
    }

    // Merge dynamic arguments with static arguments
    $term_args = array_merge( $term_args, array(
        'hide_empty' => false,
    ) );

    $terms = get_terms( $term_args );

    // Add terms to values
    if( ! empty( $terms ) && ! is_wp_error( $term_args ) ) {

        foreach( $terms as $term ) {

            $tag['values'][] = $term->name;

        }

    }

    return $tag;

}

Uses

[select mytaxname taxonomy:category]

Leave a Reply

×

Your Cart

No products in the cart.
Start shopping

About Us

Royal Technologies is a System Integration house that supports Web Design, Web Hosting, Domain Registration, Search Engine Optimizing, IT Consulting, Remote or Telephone Support and Software Development. In simpler terms it’s an IT Company dealing in various aspects of implementation and maintenance of computerization. We have learnt from experience and have molded ourselves to be complete IT Company.

CONTACT US

Location

Copyright © 2008-2024 Royal Technologies. All rights reserved.
Development by Royal Technologies