Get terms of a post but only if they’re also the child of a specific term

The question:

I have the below code successfully running on my custom post type archive pages. The only issue I have is that I want the list of ‘book_cat’ taxonomy terms for that post but ONLY if they’re also children of the taxononmy term with an id of 5.

Trying to use the post ID as a parameter isn’t working. Can anyone tell me what I’m doing wrong please?

$args = array( 'hide_empty' => '0','taxonomy' => 'book_cat', 'child_of' => 5);
$categories = get_terms($args);
if($categories){
    echo '<ul class="characters">';
    foreach($categories as $category) {
        $link = get_term_link($category);
        echo '<li>';
        $size = "thumbnail";
        $image = get_field('main_image', 'category_'.$category->term_id);
        echo '<a href="'.$link.'">';
        echo wp_get_attachment_image( $image, 'thumbnail', "", ["class" => "character"] );
        echo '</a>';
        echo '<span class="cat-title"><a href="'.$link.'">' . $category->name . '</a></span>';
        echo '</li>';
    } 
    echo '</ul>';
}    

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

If I understood right, right now you get all child terms of term with id = 5, but you need to show only terms from this list, which are attached to the post.

get_terms()
Retrieves the terms in a given taxonomy or list of taxonomies.

Try to use wp_get_post_terms() instead, which allows you to set post id.
Make sure $post->ID is available.

wp_get_post_terms()
Retrieves the terms for a post.

$args = array( 'hide_empty' => '0','taxonomy' => 'book_cat', 'child_of' => 5);
$categories = wp_get_post_terms($post->ID, 'book_cat', $args);
//rest of your code goes here.....


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment