/** * Update moodle course categories in Wordpress site. * * @access private * @param array $categories * @param string $taxonomy * @param string $meta_key * @return void */ private function update_categories($categories, $taxonomy, $meta_key) { if (empty($taxonomy) || empty($meta_key) || !taxonomy_exists($taxonomy)) { return; } $category_ids = array(); if (!empty($categories)) { foreach ($categories as $category) { $term_id = woodle_get_term_by_moodle_id($category['id'], $taxonomy, $meta_key); if (!$term_id) { $term = wp_insert_term($category['name'], $taxonomy, array('description' => $category['description'], 'slug' => "{$category['name']} {$category['id']}")); if (!is_wp_error($term)) { apply_filters("woodle_add_{$meta_key}_meta", $term['term_id'], '_category_id', $category['id'], false); apply_filters("woodle_add_{$meta_key}_meta", $term['term_id'], '_parent', $category['parent'], false); apply_filters("woodle_add_{$meta_key}_meta", $term['term_id'], '_category_path', $category['path'], false); } } else { $term = wp_update_term($term_id, $taxonomy, array('name' => $category['name'], 'slug' => "{$category['name']} {$category['id']}", 'description' => $category['description'])); if (!is_wp_error($term)) { apply_filters("woodle_update_{$meta_key}_meta", $term['term_id'], '_parent', $category['parent'], ''); apply_filters("woodle_update_{$meta_key}_meta", $term['term_id'], '_category_path', $category['path'], false); } } $category_ids[] = $category['id']; } } $terms = woodle_get_terms($taxonomy); if ($terms) { foreach ($terms as $term) { $category_id = apply_filters("woodle_get_{$meta_key}_meta", $term->term_id, '_category_id', true); if (in_array($category_id, $category_ids)) { $parent = apply_filters("woodle_get_{$meta_key}_meta", $term->term_id, '_parent', true); $parent_term_id = woodle_get_term_by_moodle_id($parent, $taxonomy, $meta_key); wp_update_term($term->term_id, $taxonomy, array('parent' => $parent_term_id)); } else { if (!empty($category_id)) { wp_delete_term($term->term_id, $taxonomy); } } } } }
/** * Returns term id by moodle category id * * @param int $category_id * @param string $taxonomy (default: null) * @param string $meta_key (default: null) * @return int */ function woodle_get_term_by_moodle_id($category_id, $taxonomy = '', $meta_key = '') { if (empty($category_id) || !is_numeric($category_id) || empty($taxonomy) || !taxonomy_exists($taxonomy) || empty($meta_key)) { return 0; } $terms = woodle_get_terms($taxonomy); //print_r($terms);die; if ($terms) { foreach ($terms as $term) { if (apply_filters("woodle_get_{$meta_key}_meta", $term->term_id, '_category_id', true) == $category_id) { return $term->term_id; } } } return 0; }