WordPress.org

Ready to get started?Download WordPress

Forums

get_category_parents with no end separator (5 posts)

  1. punkyb9
    Member
    Posted 2 years ago #

    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.

  2. vtxyzzy
    Member
    Posted 2 years ago #

    You could always remove the trailing separator:

    <?php $catstr = get_category_parents($cat, TRUE, ' / ');
    echo substr($catstr, 0, strlen($catstr) -3 ); ?>
  3. punkyb9
    Member
    Posted 2 years ago #

    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?

  4. vtxyzzy
    Member
    Posted 2 years ago #

    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;';
    }
    ?>
  5. punkyb9
    Member
    Posted 2 years ago #

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

Topic Closed

This topic has been closed to new replies.

About this Topic