Wordpress - How do I query a custom post type with a custom taxonomy?
Firs of all don't use query_posts()
ever, read more about it here: When should you use WP_Query vs query_posts() vs get_posts()?.
You have to use WP_Query
to fetch posts what you need. Read documentation for it. In your case the query could be like this:
$the_query = new WP_Query( array(
'post_type' => 'Adverts',
'tax_query' => array(
array (
'taxonomy' => 'advert_tag',
'field' => 'slug',
'terms' => 'politics',
)
),
) );
while ( $the_query->have_posts() ) :
$the_query->the_post();
// Show Posts ...
endwhile;
/* Restore original Post Data
* NB: Because we are using new WP_Query we aren't stomping on the
* original $wp_query and it does not need to be reset.
*/
wp_reset_postdata();
i am using this query to fetch custom posts (FAQs Posts) with its custom taxonomy (faq_category). since {taxonomy} parameter in WP_Query args was deprecated since v.3.1 and introduced {tax_query}. below is the code that works perfectly.
$query = new WP_Query( array(
'post_type' => 'faqs', // name of post type.
'tax_query' => array(
array(
'taxonomy' => 'faq_category', // taxonomy name
'field' => 'term_id', // term_id, slug or name
'terms' => 48, // term id, term slug or term name
)
)
) );
while ( $query->have_posts() ) : $query->the_post();
// do stuff here....
endwhile;
/**
* reset the orignal query
* we should use this to reset wp_query
*/
wp_reset_query();
Here the code that works like magic. I am fetching all posts for the custom post_type "university_unit" with custom taxonomy "unit_type" and multiple taxonomy terms as "directorate" and "office". I hope it helps out.
<?php
$args = array(
'post_type' => 'university_unit',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC',
'tax_query' => array(
array(
'taxonomy' => 'unit_type',
'field' => 'slug',
'terms' => array('directorate', 'office')
)
)
);
$Query = new WP_Query($args);
if($Query -> have_posts()):
while($Query -> have_posts()):
$Query -> the_post();
?>
<div class="cm-post-list-item">
<article>
<div class="cm-post-head">
<h3 class="cm-text-blue">
<a href="<?php the_permalink(); ?>"><?php the_title();?></a>
</h3>
</div>
<div class="cm-post-body"><?php the_excerpt();?></div>
</article>
</div>
<?php
endwhile;
else:
"No Administrative Offices Found. Try again later";
endif;
wp_reset_postdata();
?>