以下是动态填充内置选项的最新方法,可以轻松扩展以支持更多选项。
/**
* Dynamic Select List for Contact Form 7
* @usage [select name taxonomy:{$taxonomy} ...]
*
* @param Array $tag
*
* @return Array $tag
*/
function dynamic_select_list( $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;
}
add_filter( \'wpcf7_form_tag\', \'dynamic_select_list\', 10 );
以下是一种较旧/原始的方法,应被视为过时。
/** Dynamic List for Contact Form 7 **/
/** Usage: [select name term:taxonomy_name] **/
function dynamic_select_list($tag, $unused){
$options = (array)$tag[\'options\'];
foreach ($options as $option)
if (preg_match(\'%^term:([-0-9a-zA-Z_]+)$%\', $option, $matches))
$term = $matches[1];
//check if post_type is set
if(!isset($term))
return $tag;
$taxonomy = get_terms($term, array(\'hide_empty\' => 0));
if (!$taxonomy)
return $tag;
foreach ($taxonomy as $cat) {
$tag[\'raw_values\'][] = $cat->name;
$tag[\'values\'][] = $cat->name;
$tag[\'labels\'][] = $cat->name;
}
$tag[\'raw_values\'][] = \'Other\';
$tag[\'values\'][] = \'Other\';
$tag[\'labels\'][] = \'Other - Please Specify Below\';
return $tag;
}
add_filter( \'wpcf7_form_tag\', \'dynamic_select_list\', 10, 2);