Support

Account

Home Forums Front-end Issues Populate select list with values of custom field Reply To: Populate select list with values of custom field

  • There are some ways to get a list of all of the values of this field.

    The first is what you are doing, which is time consuming. Get all of the posts and loop through them all and build a list of values.

    
    $values = array();
    if ($posts) {
      foreach ($posts as $post) {
        $value = get_field('item_oem', $post->ID);
        if (!in_array($value, $values)) {
          $values[] = $value;
        }
      }
    }
    

    then you loop over the array that was built do show the options. I would not do this. Querying all of the posts to get the values is a bad idea for performance.

    The second way would be to query the DB directly

    
    // see wpdb for more information. This is dirty for an example
    global $wpdb;
    $query = 'SELECT DISTINCT meta_value
              FROM '.$wpdb->postmeta.' pm, '.$wpdb->posts.' p
              WHERE pm.meta_key = "item_oem"
                AND pm.post_id = p.ID
                AND p.post_type = "inventory"
                AND p.post_status = "publish"
              ORDER BY pm.meta_value';
    $values = $wpdb->get_results($query, 'ARRAY_A');
    

    Then you can loop over these results. This will be faster but can get the job done.

    If it is not too late I would make this oem field a custom taxonomy because taxonomies are built to do and are capable of doing what you want a lot easier and faster.