I’ve got posts that I want to echo after the post content the categories only if they’re a child of a given parent category.
Example:
Parent category: Goal
Child categories of “Goal”: brand awareness, brand engagement
If a post is categorized, I want it to echo out those category or categories:
<?php
$categories = get_the_category();
$seperator = ' ';
$output = '';
if($categories)
{
foreach($categories as $category)
{
$output .= '<a href="'.get_category_link($category->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.'</a>'.$seperator;
}
echo trim($output, $seperator);
}
?>
I’m using this, but it obviously outputs all categories, rather than just the ones that are children of the “goal” slug.
Edit: Current setup looks like this, but doesn’t seem to be working. If I use the ID, it’s fine:
<?php
$categories = get_the_category();
$seperator = ', ';
$output = '<strong>GOAL:</strong> ';
$category = get_category_by_slug('goal');
if($categories)
{
foreach( $categories as $category )
{
if ( $category->parent == $category->term_id )
$output .= '<a href="'.get_category_link($category->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.'</a>'.$seperator;
}
echo trim($output, $seperator);
}
?>
Change:
Into:
Where you replace
'123'
with the ID of the Goal category.I agree with the above answer except that it should use
get_category_by_slug()
instead of hardcoded ID’s. The comments got sort of confusing to follow because the question was also changed – so I’ve split this out into my own answer.To work this into the bit of logic you have above…
I am assuming that the
slug
of your “Goal” category is simplygoal
.What about using a conditional check?
here’s example which checks for parent category with ID (4).
Example –
you could use get_the_category_list(”,$category_id,$optional_post-ID)
http://codex.wordpress.org/Function_Reference/get_the_category_list