0

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?

3
  • The culprit is return $term->name. From the PHP manual: "If called from within a function, the return statement immediately ends execution of the current function" --> Hence your foreach loop never gets past one iteration. Collect the terms in a concatenated string. Return that after iterating over them. Commented Jul 17, 2013 at 9:04
  • As an aside, the above basically answers a new question - Milo's below answer covered your initial question entirely - it hence should be accepted, IMHO. Commented Jul 17, 2013 at 9:05
  • @JohannesPille My bad, you're definitely correct. I just accepted the answer. Also I managed to solve the shortcode issue with concatenated string as you've suggested. Thank for that!
    – Hassan
    Commented Jul 17, 2013 at 10:17

1 Answer 1

2

Put the term IDs of the current post terms in an array, and pass that as the exclude parameter to the get_terms function.

$this_post_terms = get_the_terms( $post->ID, 'your_custom_tax' );
$exclude = wp_list_pluck( $this_post_terms, 'term_id' );
$args = array(
    'exclude' => $exclude, 
);
$terms = get_terms( 'your_custom_tax', $args );
2
  • 1
    thanks for the tip about wp_list_pluck! Cool function I didn't know about. I've updated my question, please see.
    – Hassan
    Commented Jul 17, 2013 at 8:40
  • Never mind, all good now
    – Hassan
    Commented Jul 17, 2013 at 10:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.