Browse: Home / Snippets /

Get course steps taxonomy terms

Contents


Snippet #

/**
 * LearnDash Get Course Steps Taxonomy Terms
 * This utility function will gather all the steps within the course and all the taxonomy terms assigned to the steps
 * 
 * @param $course_id - integer for course ID
 * @param $course_step_types - array of course step post_types. Default is array( 'sfwd-lessons', 'sfwd-topic' )
 * @param $course_step_taxonomies - array of taxonomies to limit the return. Default will be all associated taxonomies for each post type in $course_step_types
 * @return array of taxonomy terms WP_Term
 */
function learndash_get_course_step_taxonomy_terms( $course_id = 0, $course_step_types = array( 'sfwd-lessons', 'sfwd-topic' ), $course_step_taxonomies = array() ) {
	$course_steps = learndash_get_course_steps( $course_id, $course_step_types );

	if ( !empty( $course_steps ) ) {
		$post_terms = array();
		$post_taxonomies = array();
	
		foreach( $course_steps as $course_step_id ) {
			$taxonomy_names = get_post_taxonomies( $course_step_id );
			if ( !empty( $taxonomy_names ) ) {
				foreach( $taxonomy_names as $taxonomy_name ) {
					if ( ( empty( $course_step_taxonomies ) ) || ( in_array( $taxonomy_name, $course_step_taxonomies ) ) ) {
						$terms = wp_get_post_terms( $course_step_id, $taxonomy_name, array( 'fields' => 'ids' ) );
						if ( !empty( $terms ) ) {
							$post_terms = array_merge( $post_terms, $terms );
						}
					}
				}
			}
		}
	
		if ( !empty( $post_terms ) ) {
			$post_terms = array_unique( $post_terms );
		
			$get_terms_args = array(
				'taxonomy' => $course_step_taxonomies,
				'include' => $post_terms,
				'hide_empty' => false,
			);
			if ( !empty( $course_step_taxonomies ) ) {
				$get_terms_args['taxonomy'] = $course_step_taxonomies;
			}

			$terms = get_terms( $get_terms_args ); 
			return $terms;
		}
	}
}