Support

Account

Home Forums Feature Requests Query by dropdown field label

Solving

Query by dropdown field label

  • I have a custom post type “coffee machine”.
    A coffee machine has two fields “cups min” and “cups max”.

    I want to use dropdown fields for these values so that authors can maintain the machines easily and consistent.
    The selection for min and max values should be the same for all machines.

    If i now provide a dropdown for “cups min” with e.g:
    10
    50
    180

    I get into trouble if these values change in the future. If the value 10 gets 12, i have to go through all CPT and edit and save the dropdowns again.

    So i’d better use labels and (index) values for the dropdowns:
    0 : 10
    1 : 50
    2 : 180

    If the “cups min” now changes (e.g. 10 to 12), i only have to change the label:
    0 : 12
    The value stays the same and everything is fine without going through all CPT again.

    Now the problem is, that i cant’ query the “label’s” value.
    Querying is only possible via the field’s value:

    
    'meta_query' => array(
      array(
        'key' => 'kk-cups-min',
        'value' => $userInput,
        'compare' => '<=',
        'type'    => 'NUMERIC'
      )
      ...
    ),
    

    I already contacted the support and it was said, that it’s not possible to query the labels.

    As a feature request:
    It would be nice to have the ability to query ACF dropdown labels (values)

    Best regards

  • Hi @ageibert

    I believe you can get the label and value pairs with the get_field_object() function. So you can do it like this:

    $the_input = '12'; // The input from users
    
    // Get the select field object
    $select_object = get_field_object('select_field_name');
    
    // Search the field value based on the label
    $userInput = array_search($the_input, $select_object['choices']);
    
    print_r($userInput);

    I hope this helps 🙂

  • Hi James,
    this is a great workaround.
    So i’d first do the WP_Query without limiting the results by comparing the user input and after the query i’d loop the results once more to filter the results via php.

    I need the field’s label for the WP_Query, not after the query.

    If i had two values to compare like:

    
    'meta_query' => array(
      array(
        'key' => 'kk-cups-min',
        'value' => $userInput,
        'compare' => '<=',
        'type'    => 'NUMERIC'
      ),
      array(
        'key' => 'kk-cups-max',
        'value' => $userInput,
        'compare' => '>=',
        'type'    => 'NUMERIC'
      )
      ...
    ),
    

    i’d have do loop twice to filter the results via php.

    I think this is a great solution so far.
    (it would be much more easier if one could do it all in the WP_Query, but this workaround is just fine for me now)

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.