Support

Account

Home Forums General Issues Insert a new Custom Post Type with populated ACF fields via code Reply To: Insert a new Custom Post Type with populated ACF fields via code

  • Here is an example function that will search fields and return a field key that matches the field name.

    Please note:

    1) This will only search top level fields, so no fields inside of repeaters or flex fields will be looked at.

    2) It will return the first field key where the field name matches. I think the field groups are search according to the order values of the field groups. This means that if you have two top level fields with the same name it will always return the same field key, the first one it finds. Having multiple field groups using the same field names is not uncommon, I do this all the time so that I can use the same code to get a field used for the same purpose for multiple locations. I create multiple field groups where a few fields are the same but the majority of field are different.

    3) Using this function might have unforeseen side effects depending on where it’s used that has to do with the way that ACF caches field groups and fields.

    
    <?php 
      
      function acf_field_name_to_key($field_name, $post_id=false) {
        $field_key = false;
        $post_id = acf_get_valid_post_id($post_id);
        $args = array();
        if ($post_id) {
          $args = array('post_id' => $post_id);
        }
        $field_groups = acf_get_field_groups($args);
        if (!count($field_groups)) {
          return $field_key;
        }
        foreach ($field_groups as $group) {
          $fields = acf_get_fields($group['key']);
          if (!count($fields)) {
            // no fields
            break;
          }
          foreach ($fields as $field) {
            if ($field['name'] == $name) {
              return $field['key'];
            }
          } // end foreach $fields
        } // end foreach $group
        return $field_key;
      } // end function acf_field_name_to_key
      
    ?>