I'm now using Advanced Custom Fields Plugin in wordpress.
And now I defined some Choices, and they have Choices set as below:
Field Name: time_availability
Field Type: Select
low : Once or twice
high : Several times
So, I want to enumerate these settings in the page code, like rendering:
<ul>
<li><input type="radio" name="low" /> Once or twice</li>
<li><input type="radio" name="high" /> Several times</li>
</ul>
How can I get the choices?
Seemed if calling the get_field_object($field_name)
may got the entire field settings, including the choices.
But when I call the function with the field name, the below is returned:
array(18) {
["key"]=>
string(33) "field_time_availability"
["label"]=>
string(0) ""
["name"]=>
string(27) "time_availability"
["_name"]=>
string(27) "time_availability"
["type"]=>
string(4) "text"
["order_no"]=>
int(1)
["instructions"]=>
string(0) ""
["required"]=>
int(0)
["id"]=>
string(37) "acf-field-time_availability"
["class"]=>
string(4) "text"
["conditional_logic"]=>
array(3) {
["status"]=>
int(0)
["allorany"]=>
string(3) "all"
["rules"]=>
int(0)
}
["default_value"]=>
string(0) ""
["formatting"]=>
string(4) "html"
["maxlength"]=>
string(0) ""
["placeholder"]=>
string(0) ""
["prepend"]=>
string(0) ""
["append"]=>
string(0) ""
["value"]=>
bool(false)
}
Not the expecting result.
While if I call that function with the raw field name:
get_field_object('field_55df081515e81');
It goes right!
What's the matter? What's the difference and how can I get it right using the field_name?
On ACFs site they state:
"The API will return the selected value. If you select the multiple option for this field, the API will return an array of values."
So try the following:
// get the selected value
$value = get_field('time_availability');
?>
<ul>
<li><input type="radio" name="low" <?php echo ($value == 'low'?'checked="checked"':''); ?>/> Once or twice</li>
<li><input type="radio" name="high" <?php echo ($value == 'high'?'checked="checked"':''); ?>/> Several times</li>
</ul>
If you have enabled the selection of multiple values, you should use checkboxes instead of radios.
To access the available choices, you have to get the field object.
// choose the field
$field_name = 'time_availability';
$field = get_field_object($field_name);
if( $field )
{
// build the form
echo '<select name="' . $field['key'] . '">';
foreach( $field['choices'] as $k => $v )
{
echo '<option value="' . $k . '">' . $v . '</option>';
}
echo '</select>';
}
To get the field object from a user, use this notation:
$user_id = 2; // the id of the user
$field_name = 'your_field'; // the name of the field
get_field_object($field_name, 'user_.'.$user_id)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With