I have this code:
<?php
// List subcategories of category '4'
$subcategories = get_categories('&child_of=4');
foreach ($subcategories as $subcategory) {
echo sprintf(' <a href="%s">%s</a> <span class="sep">•</span>', get_category_link($subcategory->term_id), apply_filters('get_term', $subcategory->name));
}
?>
This code retrieves a list of subcategories from category id 4. I have added this code in post loop(have_posts()
). It is showing all tagged subcategories from that category on every post's box.
What I want is to just show the subcategories from the category 4, which is tagged in that post. It shouldn't show all the subcategories from all categories tagged for all the posts.
Thanks in advance
I have this code:
<?php
// List subcategories of category '4'
$subcategories = get_categories('&child_of=4');
foreach ($subcategories as $subcategory) {
echo sprintf(' <a href="%s">%s</a> <span class="sep">•</span>', get_category_link($subcategory->term_id), apply_filters('get_term', $subcategory->name));
}
?>
This code retrieves a list of subcategories from category id 4. I have added this code in post loop(have_posts()
). It is showing all tagged subcategories from that category on every post's box.
What I want is to just show the subcategories from the category 4, which is tagged in that post. It shouldn't show all the subcategories from all categories tagged for all the posts.
Thanks in advance
Here is a function I've recently used (modified version of the code found in the codex) to display a list of the categories a post is attached to.
This function first gets the parent category to which the post belong, and that info is then fed back into wp_list_categories
to remove the parent category and to get a list of the child categories belonging to that parent
<?php
$taxonomy = 'category';
// get the term IDs assigned to post.
$post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) );
// separator between links
$separator = ', ';
$categories = get_the_category();
$parentid = $categories[0]->category_parent;
if ( !empty( $post_terms ) && !is_wp_error( $post_terms ) ) {
$term_ids = implode( ',' , $post_terms );
$terms = wp_list_categories( 'title_li=&style=none&echo=0&child_of=' . $parentid . '&taxonomy=' . $taxonomy . '&include=' . $term_ids );
$terms = rtrim( trim( str_replace( '<br />', $separator, $terms ) ), $separator );
// display post categories
echo $terms;
}
?>
To do so, you should remove the ampersand (which is used to concatenate multiple arguments) and use parent
instead of child_of
, so that only subcategories (and not deeper-nested categories) are listed:
$subcategories = get_categories( 'parent=4' );