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

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>';
}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x