How to make a post with certain taxonomy term display first before other post with only one query?

Question

I have a custom post types Courses that I want to display on my page but I want to display courses with custom taxonomy term called ‘math’ and then all the other subjects after that. I’m able to do so with two queries but that makes my code longer. Is it possible to make it one just one query?

I want my page to look like this:

  • Math
  • Math
  • Math
  • Math
  • P.E
  • Science
  • Science
  • Social Studies

Right now, I’m repeating the query and the only difference with the 2nd query is that I added the 'operator' => 'NOT IN'. Here’s what I have so far:

<?php
$args = array(
'post_type'        => 'course',
'posts_per_page'   => -1,
'order'            => 'ASC',
'orderby'          => 'name',
'post_parent' => 0,
'tax_query' => array(
    array (
        'taxonomy' => 'subject',
        'field' => 'slug',
        'terms' => array(
            'math'
        ),
    )
),
);

$the_query = new WP_query($args);

if( $the_query->have_posts() ) : 
while( $the_query->have_posts() ) : $the_query->the_post(); 
    ?>

    <div class="col"><?php the_title(); ?></div>


<?php endwhile; endif; wp_reset_query(); ?>




<?php
$arg_2 = array(
    'post_type'        => 'course',
    'posts_per_page'   => -1,
    'order'            => 'ASC',
    'orderby'          => 'name',
    'post_parent' => 0,
    'tax_query' => array(
        array (
            'taxonomy' => 'subject',
            'field' => 'slug',
            'terms' => array(
                'math'
            ),
            'operator' => 'NOT IN',
        )
    ),
);

$the_query_2 = new WP_query($arg_2);

if( $the_query_2->have_posts() ) : 
    while( $the_query_2->have_posts() ) : $the_query_2->the_post(); 
        ?>

        <div class="col"><?php the_title(); ?></div>


<?php endwhile; endif; wp_reset_query();?>

0
palekjram 1 month 2022-07-06T04:15:42-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse