You could always remove the trailing separator:
<?php $catstr = get_category_parents($cat, TRUE, ' / ');
echo substr($catstr, 0, strlen($catstr) -3 ); ?>
That works, thank you!
I’m also trying to display the same thing on single pages, but the get_category_parents code doesn’t work there.
Currently I have:
<?php
foreach((get_the_category()) as $childcat) {
$parentcat = $childcat->category_parent;
echo get_cat_name($parentcat);
}
?>
<?php
$category = get_the_category();
echo '/ ';
echo $category[0]->cat_name;
echo ' /';
?>
That works except again, I want to get rid of the final slash. And on pages with no parent category it shows the slash before as well. Any idea what I should use instead?
I believe that your code will only work when there is a single category, with or without a parent. If there is more than one category, the parent names will all be strung together with no spaces between and only the first child will be listed.
I don’t know what you want to do in those situations. The following should work, but it only prints the first parent it finds.
<?php
foreach((get_the_category()) as $childcat) {
$parentcat = $childcat->category_parent;
if ($parentcat) break; // Save only first parent
}
$sep = '';
$parentname = '';
if ($parentcat) {
$parentname = get_cat_name($parentcat);
echo $parentname;
$sep = ' / ';
}
foreach (get_the_category() as $category) {
$cat_name = $category->cat_name;
if ($cat_name != $parentname) {
echo $sep;
echo $cat_name;
}
$sep = ' / ';
}
?>
Good to know. I think this actually works perfectly for what I need to do. Thank you so much for your help!