How do I sort posts by custom taxonomy?

Question

I am trying to sort posts by custom taxonomy. I have a custom post type which is course-cpt and I have created custom taxonomies within it, I need to sort the courses by course-level (which is the taxonomy term) so that it displays like so:

  • Course Name level 1
  • Course Name level 2
  • Course Name level 3 etc

I currently have the following in my functions.php:

add_action( 'pre_get_posts', 'reorderByCourseLevel' );

function reorderByCourseLevel( $query ) {

if ( $query->is_main_query() && !is_admin() ) {
        if ( $query->is_tax() || $query->is_post_type_archive('subject') ) {
            $taxquery = array(
               'taxonomy' => 'course-level'
            );
            $query->set('tax_query', $taxquery);
            $query->set('orderby', 'title');   
            $query->set('order', 'ASC');
       }       
    }
}

Am I missing anything in my code..?

0
, , Neelam Khan 2 years 2020-01-15T08:41:14-05:00 0 Answers 55 views 0

Leave an answer

Browse
Browse