Reputation: 41
I need to get the field key by field name in WordPress in the Advanced custom fields plugin (ACF).
The field is assigned to a post. I am in the loop of the post and I want to get the field key programmatically USING field name. The reason for this is because i'm creating a form where the field name 'options' will stay the same but will have different options in a select.
I am looping over a custom post type and expecting the field 'options' to be assigned to the post (each post will have unique options and so will have a unique field key so i can't just use the field key as this would be hard-coded to potentially another posts options)...
I'm in the loop of the post which should contain the custom field 'options' so I should be able to look for field key using post id and custom field name?
EDIT: I found this: https://gist.github.com/mcguffin/81509c36a4a28d9c682e
But it doesn't seem to work?
Upvotes: 4
Views: 4811
Reputation: 176
The right way is to use acf_maybe_get_field
function, just like that:
acf_maybe_get_field( 'field_name', false, false );
The arguments are: field name
, post id
(defaults to current post) and the most important strict
which defaults to true
, but we set it to false
here to get field object even when it not yet exists for the post.
Upvotes: 7
Reputation: 191
I think it would be easier to tackle the problem from a different perspective.
You can filter the options in a select field for each post. See https://www.advancedcustomfields.com/resources/dynamically-populate-a-select-fields-choices/
function acf_load_option_field_choices( $field ) {
global $post;
$current_id = $post->ID;
switch ( $current_id ) {
case 101: //Post ID 101
$field[ 'choices' ] = array(
'ferrari' => 'Ferrari',
'lambo' => 'Lambo',
'toyota' => 'Toyota',
'volvo' => 'Volvo'
);
break;
case 202: // Post ID 202
$field[ 'choices' ] = array(
'youtube' => 'Youtube',
'facebook' => 'Facebook',
'twitter' => 'Twitter',
'stackoverflow' => 'Stack Overflow'
);
break;
}
// return the field
return $field;
}
add_filter( 'acf/load_field/name=options', 'acf_load_color_field_choices' );
At that point you could pull options from global options or wherever you like, they don't need to be hard coded. This means the heavy lifting is done before, and then in the loop just loop over the options like a normal ACF Field.
Upvotes: 0