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);
}
?>