0

I am displaying courses, enrollment, along with rooms whose capacities are greater than or equal to the enrollment. This query works, except the 'order' => 'DESC' for courses, and 'orderby' => 'meta_value_num'.

Currently, the courses are listed by title, but ascending. And, the rooms are not ordered at all. Can anyone tell me what I'm doing wrong?

$courses = new WP_Query( array( 'post_type' => 'courses', 'posts_per_page' => '-1', 'orderby' => 'title' , 'order' => 'DESC' ) );


if ( $courses->have_posts() ) {
  while ( $courses->have_posts() ) {
    $courses->the_post();

         $enr = get_post_meta(get_the_ID(), 'course_enrolled' , true);
         $cname = get_the_title();

         $rooms = new WP_Query(
                  array(
                  'posts_per_page' => -1,
                  'post_type' => 'rooms',
                  'meta_query' => array(
                        array(
                        'key' => 'room_capacity',
                        'posts_per_page' => '-1',
                        'type' => 'NUMERIC',
                        'value' => $enr,
                        'compare' => '>=',
                        //the below ordering part doesn't function as expected
                        'order' => 'DESC',
                        'orderby' => 'meta_value_num'

                        )
                      )
                    )
          );
          if ( $rooms->have_posts() ) {
            while ( $rooms->have_posts() ) {
                $rooms->the_post();


                $rname = get_the_title();
                $cap = get_post_meta(get_the_ID(), 'room_capacity' , true);

                echo 'cname: ' . $cname . ' ' . 'enrolled: ' . $enr . 'rname: ' . $rname.  'capacity: ' . $cap . '<br/>';

              }
            }




  }
} else {
    echo "Loop not working";
  }

   wp_reset_postdata();
  • order and orderby (and also posts_per_page) belong in the main query args, same level as meta_query. So 'meta_query' => array( ... ), 'order' => 'DESC', 'orderby' => 'meta_value_num' – Sally CJ Nov 22 '19 at 22:50
  • 1
    That worked perfectly. Thank you. – JennyJ Nov 22 '19 at 23:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.