Support

Account

Home Forums General Issues Get field key by field name Reply To: Get field key by field name

  • Thank you very much! I did a slight modification in order to be able to retrieve the name or the field key depending what is given, because I needed the exact opposite. I paste it here for future reference to others. Cheers!

    function acf_get_field_info( $return = 'name', $field_key, $post_id ) {
    		global $wpdb;
    		//choose name 
    		if($return == 'name'){
    			$acf_fields = $wpdb->get_results( $wpdb->prepare( "SELECT ID,post_parent,post_excerpt FROM $wpdb->posts WHERE post_name=%s AND post_type=%s" , $field_key , 'acf-field' ) );
    		}elseif($return == 'key'){
    			$acf_fields = $wpdb->get_results( $wpdb->prepare( "SELECT ID,post_parent,post_name FROM $wpdb->posts WHERE post_excerpt=%s AND post_type=%s" , $field_key , 'acf-field' ) );
    		}
    		// get all fields with that name.
    		switch ( count( $acf_fields ) ) {
    			case 0: // no such field
    				return false;
    			case 1: // just one result.
    				return $acf_fields[0]->post_excerpt;
    		}
    		// result is ambiguous
    		// get IDs of all field groups for this post
    		$field_groups_ids = array();
    		$field_groups = acf_get_field_groups( array(
    			'post_id' => $post_id,
    		) );
    		foreach ( $field_groups as $field_group )
    			$field_groups_ids[] = $field_group['ID'];
    
    		// Check if field is part of one of the field groups
    		// Return the first one.
    		foreach ( $acf_fields as $acf_field ) {
    			if ( in_array($acf_field->post_parent,$field_groups_ids) )
    				return $acf_field->post_name;
    		}
    		return false;
    	}