How to pass taxonomy terms to WP_Query along with $args?

I created a cpt and custom taxonomy associated with it. Lets say custom taxonomy name is Sports. I added terms to it - football, basketball.

Now, i want to fetch post titles tagged under football and basketball separately on same page.(Note:- i am using a custom page template to show list of articles from CPT).

$args = array(
      'post_type' = 'sports',
      'tax_query' = array(
                array(
                'taxonomy' = 'sports_category',
                'field'    = 'slug',
                'terms'    = 'football'
           ),
   ),
);

$myquery = new WP_Query($args);

So, i have successfully fetched posts for football, but if i want to fetch posts for basketball, do i have to create another query with 'terms' => 'basketball'?

Is there anyway to pass 'terms' dynamically in WP_Query along with set $args so that i don't have to write same arguments twice.

What i can think of a solution is creating a function and then storing terms in a variable which will get its value from value passed while calling function.

I want to know WP specific or efficient sokution.

Topic terms wp-query custom-taxonomy custom-post-types Wordpress

Category Web


You can do like following

              $thiscat = $wp_query->get_queried_object();//put this code

              $args = array(
               'post_type' => 'sports',
               'tax_query' => array(
               array(
                 'taxonomy' => 'sports_category',
                 'field'    => 'slug',
                'terms'    => $thiscat->slug // Pass this to slug
           ),
     ),
 );

 $myquery = new WP_Query($args);

then you can able to fetch post titles tagged under football and basketball separately on same page.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.