Get terms of a post but only if they're also the child of a specific term
-
20-05-2021 - |
質問
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>';
}
解決
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.....