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.

4
  • Where (on which template) are you running this query? Apr 1, 2015 at 3:58
  • I have created a custom template to show Post titles from cpt.
    – Mohit
    Apr 1, 2015 at 4:26
  • Look at this post. You can do the same, you just need to change the code slightly to make use wp_get_post_terms instead of get_the_category() Apr 1, 2015 at 6:24
  • I think this link could be interesting: wordpress.stackexchange.com/questions/15040/…
    – C.B.
    Jul 2, 2015 at 12:14

1 Answer 1

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.