【发布时间】:2016-10-28 10:11:35
【问题描述】:
我正在尝试通过动态获取帖子类别来修改 ACF 选择字段,以便用户可以在不同的类别之间进行选择(它用于博客页面模板)。我用的是ACF的函数,现在只返回第一个类别。
这就是我在functions.php 中得到的:
函数 acf_load_color_field_choices( $field ) {
function categoryName() {
$args = array(
'type' => 'post',
'taxonomy' => 'category',
'parent' => 0, // get top level categories
'orderby' => 'name',
'order' => 'ASC',
'hierarchical' => 1,
'pad_counts' => 0
);
$categories = get_categories( $args );
foreach ( $categories as $category ){
echo $category->name;
}
}
// reset choices
$field['choices'] = array();
// get the textarea value from options page without any formatting
$choices = categoryName();
// explode the value so that each line is a new array piece
$choices = explode("\n", $choices);
// remove any unwanted white space
$choices = array_map('trim', $choices);
// loop through array and add to field 'choices'
if( is_array($choices) ) {
foreach( $choices as $choice ) {
$field['choices'][ $choice ] = $choice;
}
}
// return the field
return $field;
}
add_filter('acf/load_field/name=blog_by_cat', 'acf_load_color_field_choices');
我也试过了:
function acf_load_cat_field_choices( $field ) {
// reset choices
$field['choices'] = array();
// get the textarea value from options page without any formatting
$choices = get_categories();
$value = get_categories();
// explode the value so that each line is a new array piece
$choices = explode("\n", $choices);
// remove any unwanted white space
$choices = array_map('trim', $choices);
// loop through array and add to field 'choices'
if( is_array($choices) ) {
foreach( $choices as $choice ) {
$field['choices'][ $value->slug ] = $choice->name;
}
}
// return the field
return $field;
这不返回任何内容
还有:
function acf_load_cat_field_choices( $field ) {
// reset choices
$field['choices'] = array();
// get the textarea value from options page without any formatting
$choices = get_categories();
// explode the value so that each line is a new array piece
$choices = explode("\n", $choices);
// remove any unwanted white space
$choices = array_map('trim', $choices);
// loop through array and add to field 'choices'
if( is_array($choices) ) {
foreach( $choices as $choice ) {
$field['choices'][$choice] = $choice;
}
}
// return the field
return $field;
}
这会返回“数组”(一次)
【问题讨论】:
标签: php wordpress categories advanced-custom-fields