Support

Account

Home Forums ACF PRO Get all field groups related to post Reply To: Get all field groups related to post

  • Here, I wrote a function that side-steps the ACF library and just grabs them from the database, just use it using post_type

    You can get post_type from ID with get_post_type( $ID )

    function get_acf_fields_post_type( $post_type )
      {
          global $wpdb;
    
          $sql = "SELECT p.ID, p.post_title, p.post_name, pm.meta_value as rule
                  FROM $wpdb->posts p 
                  LEFT JOIN $wpdb->postmeta pm 
                  ON ( p.ID = pm.post_id AND pm.meta_key = 'rule' ) 
                  WHERE p.post_type = 'acf'";
    
          $result = $wpdb->get_results($sql);
    
          $groups = array();
    
          foreach($result as $row){
    
            $rule = unserialize($row->rule);
    
            if( $rule['param'] == 'post_type' && $rule['operator'] == '==' && $rule['value'] == $post_type )
            { 
              $groups[$row->ID] = array('title'=>$row->post_title,'name'=>$row->post_name);
            }
    
          }
    
          foreach($groups as $post_id => $data)
          {   
              $fsql = "SELECT * FROM $wpdb->postmeta WHERE post_id = '$post_id' AND meta_key LIKE 'field_%';";
    
              $fields = $wpdb->get_results($fsql);
    
              $field_array = array();
              foreach($fields as $field)
              {
                $f = unserialize($field->meta_value);
                $field_array[$field->meta_key] = $f; 
              }
              $groups[$post_id]['fields'] = $field_array;
          }
    
          return $groups;
    
      }