Sometimes, the types of fields that are available by default in Contact Form 7 are just not enough. And sometimes, you want to just be able to use a shortcode when you define the form . For such situation, we can use the wpcf7_add_shortcode()
function, combined with the wpcf7_init
hook.
Documentation
The wpcf7_add_shortcode()
function takes 3 arguments:
$shortcode
, which is our shortcode name, exactly as in WordPress;$callback
, which is a function that will be called when the shortcode is encountered, exactly as in WordPress;$has_name_part
, which is boolean and false by default, but if it is set to true, then the shortcode can be used with a name, for example:'[my_shortcode field-name]'
, just how you would use a usual CF7 field:'[text* your-name]'
Find all details on the Contact Form 7 site’s documentation page: Adding a custom form-tag.
Example
add_action( 'wpcf7_init', 'create_my_custom_cf7_shortcodes' );
function create_my_custom_cf7_shortcodes(){
wpcf7_add_shortcode( 'lots_of_checkboxes', 'render_checkboxes' );
}
function render_checkboxes(){
// Construct checkboxes HTML here...
return $html;
}
Now we can use this when we are defining the form fields: [lots_of_checkboxes]
, which will output whatever the render_checkboxes()
function decides.