I have a custom field on wordpress that defines a select option
one : First
two : Second
three : Third
four : Fourth
I am trying to call these options on the frontend in a select form i.e.
<select id="filters">
<option value="*">show all</option>
<option value="one">First</option>
<option value="two">Two</option>
<option value="three">Third</option>
<option value="four"Fourth</option>
</select>
This is what i got so far and it doesnt seem to be working:
<?php
$field_name = "team_category";
$field = get_field_object($field_name);
foreach($field){
echo $field['label'] . ': ' . $field['value'];
}
?>
The ACF documentation says get_field_object() can have up to three parameters, while the second one is the Post ID. If no Post ID is used, it will use the current one, which you also retrieve with get_the_ID().
But probably, you want these options on another page (for example, a search page, you develop). So lets say, you create a page template. What you want to search are posts with the post_type ‘teams’. So, the post_type ‘page’ has no custom fields called “team_category” and with the current post ID no object will be returned.
What you need is a Post ID of a post which actually contains the searched field. And this should work dynamically.
Lets try
I think this might be something closer to what you’re looking for.
I know this is an old question, but wanted to throw out my answer for others who may find this. There are a couple problems with your code:
According to the ACF docs for get_field_object(), they say that “In some circumstances it may be necessary to load a field by its key, such as when a value has not yet been saved.” I have found that the field name does not work when trying to retrieve a field object outside of a loop (which is what you’re doing here with trying to show all options within a field, not just those related to a specific post).
Another challenge is that the field key can differ across environments (local, staging, production, etc) unless you sync your databases. So here’s a function that can help you find the field key by field name anytime you need to use it in a function such as get_field_object():
Will return the field key from name and group, or null if none exists.
Usage:
See full answer by @Chris about why the group name is important in How to get Advanced Custom Fields field key from WordPress database?
Then your code would be:
choices
. So to get those you need to use: