Browse: Home / Snippets /

Include LearnDash custom post types in WP Category and Post Tag archives

Contents


Snippet #

Important: All snippets are provided as-is without support or guarantees. These snippets are provided as guidelines for advanced users looking to customize LearnDash. For any additional help or support with these snippets, we recommend reaching out to a LearnDash Expert.

/**
 * LearnDash include custom post types in WP Category and Post Tag archives
 */
add_action( 'pre_get_posts', function( $post_query ) {

	// Ensure this is the main query and it is for an archive page.
	if ( ( $post_query->is_main_query() ) && ( $post_query->is_archive ) ) {

		// Only apply IF we are not querying a specific post type already.
		if ( ! isset( $post_query->query['post_type'] ) ) {
			global $sfwd_lms;

			/** Start building a list of post_types from LD. Remember each of the LD
			 * post types (sfwd-courses, sfwd-lessons, sfwd-topic and sfwd-quiz ) can
			 * each be associated with the WP Category and Post Tag taxonomies.
			 */
			$ld_post_types = array( 'sfwd-courses', 'sfwd-lessons', 'sfwd-topic', 'sfwd-quiz' );

			// Holder for the LD post types we will be including in the WP Query
			$post_types = array( );

			if ( ( isset( $post_query->query['category_name'] ) ) && ( ! empty( $post_query->query['category_name'] ) ) 
			|| ( isset( $post_query->query['tag'] ) ) && ( ! empty( $post_query->query['tag'] ) ) ) {

				foreach( $ld_post_types as $ld_post_type ) {
					// Ensure we have a valid post type.
					$ld_post_type_object = get_post_type_object( $ld_post_type );
					if ( ( $ld_post_type_object ) && ( is_a( $ld_post_type_object, 'WP_Post_Type' ) ) ) {

						// AND that the post type that the 'public' and 'has_archive' settings are true.
						if ( ( true === $ld_post_type_object->public ) && ( true === $ld_post_type_object->has_archive ) ) {
							$ld_post_type_taxonomies = $sfwd_lms->get_post_args_section( $ld_post_type, 'taxonomies' );
							if ( ( isset( $post_query->query['category_name'] ) ) && ( ! empty( $post_query->query['category_name'] ) ) && ( isset( $ld_post_type_taxonomies['category'] ) ) ) {
								$post_types[] = $ld_post_type;
							} else if ( ( isset( $post_query->query['tag'] ) ) && ( ! empty( $post_query->query['tag'] ) ) && ( isset( $ld_post_type_taxonomies['post_tag'] ) ) ) {
								$post_types[] = $ld_post_type;
							}
						}
					}
				}
			}

			// Finally here if we have some LD post types that use this taxonomy they are included in the query.
			if ( ! empty( $post_types ) ) {
				// Sort of a hack. By default when this flter is called the 'post_type' is empty. But we want to include the 'post' post type. 
				$post_types[] = 'post';
				$post_query->set( 'post_type', $post_types ); 
			}
		}
	}
}, 1 );