I have been trying to output content of all post-types (Posts, Pages and CPTs) based on a term of a custom taxonomy that they must share (meaning if they don’t share that particular term, the output should not include that post-type).
Here is what I have so far:
$term_list = wp_get_post_terms($post->ID, 'persons', array('fields' => 'names')); // persons is the custom taxonomy
$args = array(
'post_type' => array( 'post', 'page', 'profile', 'letter' ), // profile and letter are CPTs
'tax_query' => array(
array(
'taxonomy' => 'persons',
'field' => 'slug',
'terms' => $term_list
)
),
'post__not_in'=>array($post->ID)
);
$related_content = new WP_Query( $args );
if ( $related_content->have_posts() ) {
echo __('Related Content (profiles, pages, articles, letters):', 'teselle');
echo '<ul class="related-content">';
while ($related_content->have_posts()) {
$related_content->the_post();
echo '<li><a href="' . esc_url( get_permalink() ) . '">' . get_the_title() . '</a></li>';
} // endwhile
echo '</ul>';
} // endif
wp_reset_query(); wp_reset_postdata();
The problem with the above code is that it outputs too much.
If I fill in the exact slug of the term I need, for example 'terms' => 'the-exact-slug'
, it works perfect, but I really need it to be a variable.
Can someone point out what my mistake is in the above code?
Thanks!
we meet here again 🙂
Try using this:
and
AFAIK, the
tax_query
accepts field byid
orslug
only (see here. And thewp_get_post_terms
accepts onlynames
(not slug),ids
andall
. So the match between them is onlyid
.Update
If you need
slug
, use this:You might try the slugs instead of the names, i.e.
instead of
since your are using
in the tax query.
EDIT:
I added posts_per_page to return all results and use ids in the wp_get_post_terms and id in the tax_query.