public function get_export_data_for_posts($post_ids) { $posts_data = array(); $field_names = array(); $result = array(); /** * Fetch posts and get the possible field names for later use */ foreach ($post_ids as $post_id) { /** * Fetch post main data, because we need the subject and author data for the feedback form. */ $post_real_data = $this->get_parsed_field_contents_of_post($post_id); /** * If `$post_real_data` is not an array or there is no `_feedback_subject` set, * then something must be wrong with the feedback post. Skip it. */ if (!is_array($post_real_data) || !isset($post_real_data['_feedback_subject'])) { continue; } /** * Fetch main post comment. This is from the default textarea fields. * If it is non-empty, then we add it to data, otherwise skip it. */ $post_comment_content = $this->get_post_content_for_csv_export($post_id); if (!empty($post_comment_content)) { $post_real_data['_feedback_main_comment'] = $post_comment_content; } /** * Map parsed fields to proper field names */ $mapped_fields = $this->map_parsed_field_contents_of_post_to_field_names($post_real_data); /** * Fetch post meta data. */ $post_meta_data = $this->get_post_meta_for_csv_export($post_id); /** * If `$post_meta_data` is not an array or if it is empty, then there is no * extra feedback to work with. Create an empty array. */ if (!is_array($post_meta_data) || empty($post_meta_data)) { $post_meta_data = array(); } /** * Prepend the feedback subject to the list of fields. */ $post_meta_data = array_merge($mapped_fields, $post_meta_data); /** * Save post metadata for later usage. */ $posts_data[$post_id] = $post_meta_data; /** * Save field names, so we can use them as header fields later in the CSV. */ $field_names = array_merge($field_names, array_keys($post_meta_data)); } /** * Make sure the field names are unique, because we don't want duplicate data. */ $field_names = array_unique($field_names); /** * Sort the field names by the field id number */ sort($field_names, SORT_NUMERIC); /** * Loop through every post, which is essentially CSV row. */ foreach ($posts_data as $post_id => $single_post_data) { /** * Go through all the possible fields and check if the field is available * in the current post. * * If it is - add the data as a value. * If it is not - add an empty string, which is just a placeholder in the CSV. */ foreach ($field_names as $single_field_name) { if (isset($single_post_data[$single_field_name]) && !empty($single_post_data[$single_field_name])) { $result[$single_field_name][] = trim($single_post_data[$single_field_name]); } else { $result[$single_field_name][] = ''; } } } return $result; }