Reputation: 3853
I started this PHP function. This function is to populate a dropdown select menu in WordPress.
The acf/load_field hook helps me easily hook this in. See documentation here. http://www.advancedcustomfields.com/resources/filters/acfload_field/
This is my function which uses get_posts
to query my circuit
post_type. This bit works fine.
See below...
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');
The problem I am having is that...
$field['choices'] = array(
0 => 'Select a circuit...'
);
is not joining onto the front of this...
foreach($circuits as $circuit){
$field['choices'] = array(
$circuit->post_title => $circuit->post_title
);
}
Only the $circuits foreach
is showing in my dropdown, I would like 'Select a circuit' to appear as the first option in the dropdown select menu.
Can anyone help me understand where I am going wrong?
Upvotes: 1
Views: 359
Reputation: 15603
Use this:
$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);
OUTPUT:
Array
(
[choices] => Array
(
[0] => Select a circuit...
//and other fields
//with the 0 index value
//same as you are requiring
)
)
Upvotes: 1
Reputation: 639
When you use =, it replaces the current value with the one after the = sign. You're replacing the whole value of $field['choices'] each time you assign a new value.
You probably want to do something like
foreach($circuits as $circuit){
$field['choices'][$circuit->post_title] = $circuit->post_title;
}
By the way, the line $field['choices'] = array();
is useless in your code, as you change the value in the following line.
Upvotes: 1