Browse: Home / Snippets /

Add LearnDash course category to body class

Contents


Snippet #

// Output LearnDash classes inside of WP Body Class
add_filter('body_class','add_category_to_single');
function add_category_to_single($classes) {
	if (is_single() ) {
		global $post;
		// a) Ensure $post is not empty. 
		// b) Ensure $post is a WP_Post object.
		// c) Ensure $post is a LD Course or Lesson or Topic.
		if ( ( $post ) && ( is_a( $post, 'WP_Post' ) ) ) {
			if ( $post->post_type == 'sfwd-courses' ) { 
				// Get the post terms from 'ld_course_category'. 
				$terms = get_the_terms( $post->ID, 'ld_course_category' ); 
			}
			else if ( $post->post_type == 'sfwd-lessons' ) { // Get the post terms from 'ld_lessons_category'. 
				$terms = get_the_terms( $post->ID, 'ld_lesson_category' ); 
			}
			else if ( $post->post_type == 'sfwd-topic' ) { // Get the post terms from 'ld_topic_category'. 
				$terms = get_the_terms( $post->ID, 'ld_topic_category' ) ; 
			}
			// Check that there are terms and not an error. 
			if ( ( isset( $terms ) ) && ( ! is_wp_error( $terms ) ) ) {
				foreach( $terms as $category ) { 
					// add category slug to the $classes array 
					$classes[] = $category->slug; 
				}
			}
		}
	}

	// return the $classes array
	return $classes;
}