Hi, I have a problem with showing categories to which post is assigned. I would like to show only categories from a certain parent category. For example: I have categories: - Food (ID 1) o Fruit (ID 2) o Vegetables (ID 3) o Meat (ID 4) - Course (ID 5) o Breakfast (ID 6) o Lunch (ID 7) o Dinner (ID 8) Post is added to categories: Food, Fruit, Course and Breakfast. Now I would like to show on each post page what type of food post is. So I would like it to say »Fruit«. (show category where parent is ID 5) I know it's something to do with: <?php the_category( $separator, $parents, $post_id ); ?> , but I have no idea how to actually make it happen. Can you please help me? Thank you very much in advance!
Just use <?php the_category(', '); ?> PHP: where you want to show it. make sure it is within the loop. It will show category name, and will list them by comma separated if there are more than one category for any post.
post ID is not the problem. I want it to show only category Fruit. So I would need to set it something like <?php the_category( ', ', 1 ); ?> where 1 would be ID of the category from which I would like to show the sub-category (fruit in the example case). Update: <?php the_category('child_of=1'); ?> This code is very close to what I need. But it shows all categories that are child of category with ID 1. I would like it to show only categories that are child of categoriy with ID 1 and that particular post is added in.
What I guess, you want to show only the child category name for any post? Eg: You want to show only Fruit, instead of Food > Fruit? If this is the case, then just select "Fruit" as category in post editor, not "Food". Select only "Fruit" as category and use the first code I have given you.
Here is the solution: <?php foreach((get_the_category()) as $childcat) { if (cat_is_ancestor_of(909, $childcat)) { echo '<a href="'.get_category_link($childcat->cat_ID).'">'; echo $childcat->cat_name . '</a>'; }} ?> PHP: 909 is the parent category ID