Contact Form 7: Add Custom Data Providers to Select Elements/Tags

wordpress, wpcf7, select, values, database, lists, callback, programmatically

Every WordPress Power User knows the awesome Contact Form 7 plugin. It is (one of) the best plugins to create custom forms without any PHP knowledge – especially useful for endusers/customers.

But sometimes you need to create select list values programmatically. Unfortunately the Contact Form 7 Docs are very poor in matter of advanced use cases including the build-in filter hooks.

WPCF7 Form Editor#

Just add a unique name to the data attribute – in this example my.data.provider. This allows you to match the element within the filter hook!

<p>
<label> My List
    [select mylist include_blank data:my.data.provider]
</label>
</p>

Filter Hook#

Roll the drums…the magical filter hook wpcf7_form_tag_data_option allows you to alter the options list and add options/values to the select list within a simple callback

add_filter('wpcf7_form_tag_data_option', function($n, $options, $args){
    // special data provider tag found ?
    if (in_array('my.data.provider', $options)){
        return get_my_value_list();
    }

    // default - do not apply any changes within the options
    return null;
}, 10, 3);

Well, thats it!