• Does anyone know how to display the parent category and then sub-category with a separator in between, but not at the end of the line?

    I’m using this:
    <?php echo get_category_parents($cat, TRUE, ' / '); ?>

    Which displays: Parent Category / Sub-Category /
    But I want it to display Parent Category / Sub-Category

    I’ve looked all over and can’t find any other code that works.

Viewing 4 replies - 1 through 4 (of 4 total)
  • You could always remove the trailing separator:

    <?php $catstr = get_category_parents($cat, TRUE, ' / ');
    echo substr($catstr, 0, strlen($catstr) -3 ); ?>
    Thread Starter punkyb9

    (@punkyb9)

    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 '/&nbsp;';
    echo $category[0]->cat_name;
    echo '&nbsp;/';
    ?>

    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 = '&nbsp;/&nbsp;';
    }
    foreach (get_the_category() as $category) {
       $cat_name = $category->cat_name;
       if ($cat_name != $parentname) {
          echo $sep;
          echo $cat_name;
       }
       $sep = '&nbsp;/&nbsp;';
    }
    ?>
    Thread Starter punkyb9

    (@punkyb9)

    Good to know. I think this actually works perfectly for what I need to do. Thank you so much for your help!

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘get_category_parents with no end separator’ is closed to new replies.