Reputation: 157
I'm listing related pages based on category. This is what I'm using to list all related categories. What I'm trying to do is hide the entire block if it doesn't return any categories. I'm not sure how to do that with the foreach.
<h3>Related Category</h3>
<ul>
<?php foreach((get_the_category()) as $catCS) {
if($catCS->parent == 4){ ?>
<li><a href="<?php echo get_permalink(46); ?><?php echo $catCS->slug; ?>"><?php echo $catCS->cat_name; ?></a></li>
<?php }
} ?>
</ul>
Upvotes: 0
Views: 937
Reputation: 19528
Not sure if you know, but WordPress have a command to get parent categories get_category_parents
, so if you use that you could use it like this:
<?php
$result = get_category_parents($cat, true, '</li><li>');
$result = substr($result, 0, -4);
if(!is_wp_error($result))
{
?>
<h3>Related Category</h3>
<ul>
<li><?php echo $result; ?>
</ul>
<?php
}
?>
NOTE: substr
is a small hack to remove the last empty <li>
opening due to how I am using </li><li>
as a separator.
This is untested, but you could filter the current array into a resulting array and test if that is empty or not.
<?php
# save the result
$categories = array();
# fill $categories if any match
foreach ((get_the_category()) as $cat)
{
if($cat->parent == 4)
{
$categories[] = $cat;
}
}
# print nothing if $categories is empty
if (!empty($categories))
{
?>
<h3>Related Category</h3>
<ul>
<?php
foreach($categories as $catCS)
{
?>
<li><a href="<?php echo get_permalink(46); ?><?php echo $catCS->slug; ?>"><?php echo $catCS->cat_name; ?></a></li>
<?php
}
?>
</ul>
<?php
}
?>
There might be a better way but this should work.
Upvotes: 1