0

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>';
}    
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.....
4
  • 1
    Actually, wp_get_post_terms(), although indirectly, also uses get_terms() and you can pass a post ID to get_terms() using the object_ids argument, e.g. get_terms( 'taxonomy=book_cat&object_ids=123' ). But I'm not sure if @friendlyllama already tried that doing that.
    – Sally CJ
    May 13 '21 at 15:06
  • Why it is inderectly?
    – anton
    May 14 '21 at 12:42
  • wp_get_post_terms() uses wp_get_object_terms() which is the one that calls get_terms().
    – Sally CJ
    May 14 '21 at 12:49
  • 1
    Ok, will keep in mind)
    – anton
    May 14 '21 at 13:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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