13

I've seen how to get lists of fields by entity and bundle with field_info_instances() and field_info_field(), but I'm not seeing a way to get all fields of a particular type.

I was able to cook this up to do exactly what I want:

function field_get_fields_of_type($type) {
  $fields_info = field_info_instances();
  $return = array();
  foreach ($fields_info as $entity => $bundles) {
    foreach ($bundles as $bundle => $fields) {
      foreach ($fields as $field_name => $info) {
        $more_info_because_type_isnt_included = field_info_field($field_name);
        if ( $more_info_because_type_isnt_included['type'] == $type) {
          $return[$field_name] = $more_info_because_type_isnt_included;
        }
      }
    }
  }
  return $return;
}

dpm(field_get_fields_of_type('entityreference')); // prints out all entityreference fields

But that seems to be an awful lot of code, and and awful lot of looping to get something that should probably be reachable through the field API.

Does anyone know of a Field API function that will more efficiently retrieve the data I'm looking for?

23

I came across this the other day and remembered seeing this question, so here it is, a somehow very unknown function (I have neveer seen anyone mention it in a blog or anything):

field_read_fields()

and the companion function:

field_read_instances()

For example, get all taxonomy term fields:

$taxonomy_fields = field_read_fields(array('type' => 'taxonomy_term_reference'));

Or get the instances for a field with the a machine name of field_image:

$image_field_instances = field_read_instances(array('field_name' => 'field_image'));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.