我找到了另一篇文章,其中包含了用分类法的术语动态填充CF7下拉列表的代码,我已经让它正常工作了,但我希望这些术语不仅都在分类法中,而且只与它所在的文章相关。
为了给它更多的上下文,这是一个职位公告上的申请表。自定义职位类型是工作列表。我有位置分类法。这些术语被分配给一个职位。我只希望选定的术语显示在此下拉列表中。
这是我的代码:
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 );
SO网友:Aurovrata
使用Smart Grid layout extension. 动态标记可以获取3个数据源(给定的分类法或该分类法内的分支、文章标题列表或过滤挂钩函数的结果)。使用过滤器挂钩将下拉列表填充为,
add_filter(\'cf7sg_dynamic_dropdown_custom_options\', \'filter_options\',10,3);
function filter_options($options, $field_name, $form_key){
if($form_key != \'my-form\') return $options; //check this is the correct form.
if($field_name != \'custom-dropdown\') return $options; //check this is the correct field.
$options = array();
//get your terms
$terms = get_terms( $term_args );
// Add terms to values
if( ! empty( $terms ) && ! is_wp_error( $term_args ) ) {
foreach( $terms as $term ) {
//this is the <option value="">label</opton> value->label pairs.
$options[$term->id] = $term->name;
}
}
return $options;
}