I’m using Advanced Custom Fields with post-type. I have some select custom fields, and I want to show all the label choices from each field.
I’ve tried this way.
I'm throwing another option into the mix. I think the existing answers are good, but unless you look at the parent group, you will never get a reliable field key because the field name can exist across multiple groups.
For example, lets say you have two custom groups - one for post type books, and one for custom post type movies. Both groups have added a field called title.
In the database, both are stored with post_except = 'title' and post_type = 'acf-field'. Two entries with the same post_except, so any query relying only on post_except will be wrong, wildcard or not.
Any query relying on post id is not great either, as a post might not always exist to pass in.
So you need to pass in a combination of field and group to get the field key from the name. This snippet works well for me:
if (! function_exists('acf_field_from_name')) {
function acf_field_from_name($field, $group)
{
global $wpdb;
return $wpdb->get_var($wpdb->prepare("
SELECT post.post_name as field_name
FROM $wpdb->posts AS post
LEFT JOIN $wpdb->posts AS parent
ON post.post_parent = parent.id
WHERE post.post_excerpt = %s
AND post.post_type = 'acf-field'
AND parent.post_excerpt = %s
AND parent.post_type = 'acf-field-group'
", $field, $group));
}
}
Will return the field key from name and group, or null if none exists.
Usage:
acf_field_from_name('title', 'movie-fields'); // returns field_3333333333333
acf_field_from_name('title', 'book-fields'); // returns field_4444444444444
acf_field_from_name('plumbus', 'movie'); // returns null