WordPress custom taxonomy query to list custom post types tagged with a taxonomy term from a custom vocabulary.
WordPress custom taxonomy query to get posts
The following snippet lists all posts tagged with a certain term from a custom vocabulary.
In this example I have a custom post type pods_cpt_people
and a custom vocabulary pods_tax_people_type
. In this vocabulary i have a term with the term slug the-slug.
The snippet will list all posts of this custom post type tagged with the-slug taxonomy term.
<?php
// Query Arguments
$args = array(
'post_type' => 'pods_cpt_people', // the post type
'tax_query' => array(
array(
'taxonomy' => 'pods_tax_people_type', // the custom vocabulary
'field' => 'slug',
'terms' => array('the-slug'), // provide the term slugs
),
),
);
// The query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
echo '<h2> List of posts tagged with this tag </h2>';
echo '<ul>';
$html_list_items = '';
while ( $the_query->have_posts() ) {
$the_query->the_post();
$html_list_items .= '<li>';
$html_list_items .= '<a href="' . get_permalink() . '">';
$html_list_items .= get_the_title();
$html_list_items .= '</a>';
$html_list_items .= '</li>';
}
echo $html_list_items;
echo '</ul>';
} else {
// no posts found
}
wp_reset_postdata(); // reset global $post;
?>
?>
Please ♥ like the page if you found this useful!
I was hoping to do this for a term under a taxonomy used in multiple custom post-types. Alas, no posts found when I know there are 7 when I go to https:// mydomain /news-taxonomy/featured/
// Query Arguments
$args = array(
‘post_type’ => ‘*’, // the post type
‘tax_query’ => array(
array(
‘taxonomy’ => ‘news-taxonomy’, // the custom vocabulary
‘field’ => ‘slug’,
‘terms’ => array(‘featured,news-item’), // provide the term slugs
),
),
);
Maybe using “Toolset” adds a layer of confusion. I need to learn more about how this all works. Thanks for getting me started.
Hi Leif,
Try ‘post_type’ = ‘any’ or ‘post_type’ = array(‘post_type_1’, ‘post_type_2’) so it’s faster since there are a lot of WP hidden post types like media, comments etc.
and
have the term slugs be separate values
‘terms’ => array(‘featured’,’news-item’),
each term slug wrapped in it’s own quotes, as separate array item string values
instead of ‘terms’ => array(‘featured,news-item’), only one string value
something like this.
Lehel
This is plain WP core stuff so no extra plugin should have too much affect on it.