1

我启动了这个 PHP 函数。此功能用于填充 WordPress 中的下拉选择菜单。

acf/load_field 钩子可以帮助我轻松地将其钩入。请参阅此处的文档。http://www.advancedcustomfields.com/resources/filters/acfload_field/

这是我get_posts用来查询我的circuitpost_type 的函数。这一点工作正常。

见下文...

function my_circuit_field( $field )
{
    $circuits = get_posts(array(
        "post_type" => "circuit",
        "post_status" => "publish",
        "orderby" => "menu_order",
        "order" => "ASC",
        "posts_per_page"  => -1
    ));
    $field['choices'] = array();
    $field['choices'] = array(
        0 => 'Select a circuit...'
    );
    foreach($circuits as $circuit){
        $field['choices'] = array(
            $circuit->post_title => $circuit->post_title
        );
    }       
    return $field;
}
add_filter('acf/load_field/name=event_calendar_circuit', 'my_circuit_field');



我遇到的问题是...

$field['choices'] = array(
    0 => 'Select a circuit...'
);

没有加入到这个的前面......

foreach($circuits as $circuit){
    $field['choices'] = array(
         $circuit->post_title => $circuit->post_title
    );
}


只有$circuits foreach显示在我的下拉列表中,我希望“选择电路”作为下拉选择菜单中的第一个选项出现。

谁能帮我理解我哪里出错了?

4

2 回答 2

1

当您使用 = 时,它会将当前值替换为 = 符号后面的值。每次分配新值时,您都会替换 $field['choices'] 的整个值。

你可能想做类似的事情

foreach($circuits as $circuit){
    $field['choices'][$circuit->post_title] = $circuit->post_title;
}

顺便说一句,该行在$field['choices'] = array();您的代码中是无用的,因为您更改了以下行中的值。

于 2013-09-23T13:25:17.913 回答
1

用这个:

$field['choices'] = array(
    0 => 'Select a circuit...'
);
$arr = array();
foreach($circuits as $circuit){
    $arr = array(
       $circuit->post_title => $circuit->post_title
    );
    $field['choices'] = array_merge($field['choices'],$arr);
}
print_r($field);

输出:

Array
(
    [choices] => Array
        (
            [0] => Select a circuit...
            //and other fields 
            //with the 0 index value
            //same as you are requiring
        )
)
于 2013-09-23T13:20:53.503 回答