Support

Account

Home Forums Front-end Issues Get option labels without post/user ID

Solving

Get option labels without post/user ID

  • Hi!

    I’m about to built a frontend navigation showing all possible values of a <select> field I added to the user profile page via ACF.

    Now I’m looking for a way to get the field’s option labels by their values, f.e.:
    Field name: ‘country’
    Option 1 name: ‘fr’,
    Option 1 label: ‘France’

    if want to get ‘France’ by ‘fr’.

    get_field_object( 'country' ) is returning null since it’s awaiting a post / user ID. But since I’m displaying the nav outside of a post / the loop there is no ID I can query with.

    Any ideas?

  • get_field_object requires the field key if you are not referencing a saved value. The field key looks something like: field_53beaa2f69615

    In the Edit Field Group screen:
    Screen Options (window shade) > Show Field Key: Yes

    One you have it:

    $field = get_field_object($field_key);
    echo $field['choices']['fr'];

    foreach( $field['choices'] as $name => $label ) { ... }

    For more: http://www.advancedcustomfields.com/resources/get_field_object/

  • Wouldn’t that mean hard coding these field keys into my code?

    In the meantime I ended up querying the database like this:

    
    function get_field_label( $field, $value ) {
        global $wpdb;
    
        $label = '';
        $field = $wpdb->get_col( $wpdb->prepare( "
            SELECT post_content FROM {$wpdb->posts}
            WHERE post_excerpt = '%s' 
            AND post_type = 'acf-field'
        ", $field ) );
    
        if( $field ) {
            $options = unserialize( $field[0] );
            $choices = $options['choices'];
            $label = $choices[$value];
        }
    
        return $label;   
    }
    
Viewing 3 posts - 1 through 3 (of 3 total)

The topic ‘Get option labels without post/user ID’ is closed to new replies.