How to output content based on same custom taxonomy?

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!

2 Answers
2

we meet here again 🙂

Try using this:

$term_list = wp_get_post_terms( $post->ID, 'persons', array( 'fields' => 'ids' ) );

and

'tax_query' => array(
     array(
         'taxonomy' => 'persons',
         'field' => 'id',
         'terms' => $term_list
         )
     ),

AFAIK, the tax_query accepts field by id or slug only (see here. And the wp_get_post_terms accepts only names (not slug), ids and all. So the match between them is only id.

Update

If you need slug, use this:

$terms = wp_get_post_terms( $post->ID, 'persons' );
$term_slugs = wp_list_pluck( $terms, 'slug' );

Leave a Comment