Home Forums General Issues How to get the selected values only from a select field?


How to get the selected values only from a select field?

  • Hello,

    I’m using a select field in ACF, the field is for selecting a city in the UK, so I have a big list of cities in that custom field. I then use this field in pages, each page should have a city.

    What I want to do is to make a filter option in the index page and I don’t want all the cities to be visible, I just want the cities that has been selected in a page.

    Example: I have 20 pages, 10 pages selected “London” and the other 10 pages selected “Liverpool”, in the index I don’t want all the options to be visible in the select menu, I just want “London” and “Liverpool” that has been already selected in pages.

    How can I do that?


  • You need to do a query of all of the posts where this field is used and then loop through all of the posts to collect a list of the values that are actually used. The only place that information is stored is in the _postmeta table related to each post.

    For example:

    global $post;
    $cities = array();
    $args = array(
      'post_type' => 'page',
      'posts_per_page' => -1
    $query = new WP_Query($args);
    if ($query->have_posts()) {
      while ($query->have_posts()) {
        $city= get_field('city-field-name');
        if (!in_array($cities)) {
          $cities[] = $city;
  • Thank you for the help, your code solved my question but there is a small error.

    it should be if (!in_array($city, $cities)) { not if (!in_array($cities)) {

    Thank you.

  • Sorry for the typo, that happens sometimes when I type code into the editor, I’m used to a coding tool that flags missing arguments like that.

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

The topic ‘How to get the selected values only from a select field?’ is closed to new replies.