0

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.

0

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.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.