Is it possible to retrieve all the terms of a custom hierarchical taxonomy that do not belong to the current post? Perhaps by using wp_get_post_terms()
? I recently stumbled upon this unusual need.
Basically, if my custom taxonomy contain the terms (term1, term2, term3, etc.), I want to show in the single post page that this post belongs to term1 and term2 but not term3 etc.
EDIT: I am having difficulty implementing this in a shortcode. I have this code:
add_shortcode( 'my-no-terms', 'no_terms_func' );
function no_terms_func() {
$this_post_terms = get_the_terms( $post->ID, 'my-tax-slug' );
$exclude = wp_list_pluck( $this_post_terms, 'term_id' );
$args = array(
'exclude' => $exclude,
);
$terms = get_terms( 'my-tax-slug', $args );
foreach ( $terms as $term ) {
return $term->name;
}
}
But this is only outputting the first term, not the whole list of terms. Where's the culprit?
return $term->name
. From the PHP manual: "If called from within a function, the return statement immediately ends execution of the current function" --> Hence yourforeach
loop never gets past one iteration. Collect the terms in a concatenated string. Return that after iterating over them.