1

Below it's my code to show list of categories:

foreach((get_the_category()) as $childcat) {
                    if (cat_is_ancestor_of(2, $childcat)) {
                        echo '<a href="'.get_category_link($childcat->cat_ID).'">';
                        echo $childcat->cat_name . '</a> / ';
                    }
                }

This code give me results like this: category1 / category2 / category 3 /

But i want to have result without last mark:

category1 / category2 / category 3

I know i should use rtrim but i don't know how to do this in this case

adkoski
  • 81
  • 9
  • You can use rtrim and pass the second parameter which is a list of characters to trim. Example: `rtrim($string, '/')`. You would want to concatenate to a string instead of echo'ing in the loop. Then rtrim after the loop and echo that. – Jonathan Jul 31 '18 at 19:54
  • https://stackoverflow.com/questions/665135/find-the-last-element-of-an-array-while-using-a-foreach-loop-in-php you could use this – Hozikimaru Jul 31 '18 at 19:54
  • i don't know how to use rtrim with my code :/ – adkoski Jul 31 '18 at 20:03

1 Answers1

3

If you collect your links in an array, you can then use php's implode function to glue the elements in your array together with whatever separator your require.

The neat thing about implode is that it doesn't add the separator before the first element or after the last, only in between elements, which is exactly what you need.

http://php.net/manual/en/function.implode.php

$links = array();

foreach((get_the_category()) as $childcat) {
    if (cat_is_ancestor_of(2, $childcat)) {
        $links[] = '<a href="'.get_category_link($childcat->cat_ID).'">' . $childcat->cat_name . '</a>';
    }
}

echo implode(' / ', $links);
Marleen
  • 2,245
  • 2
  • 13
  • 23
  • I would upvote but you didn't explain a single thing in your answer. OP is obviously a novice, they don't understand what this code is doing, you are taking away a chance to teach them something they didn't know. – GrumpyCrouton Jul 31 '18 at 20:15
  • @GrumpyCrouton added an explanation. English isn't my first language, so I didn't know if I would be able to describe the function's workings properly in English, that's why I left it out. Hopefully what I've written now make sense to anyone reading it. :) – Marleen Jul 31 '18 at 20:28
  • @Stanzi1791 Perfect, definitely upvote worthy in my opinion. Thank you for your contribution :) You should always try to explain your code rather than just not at all, even if you think it won't make sense. I think your explanation is actually great, better than a lot I've seen. – GrumpyCrouton Jul 31 '18 at 20:29
  • Thanks for the upvote, I will keep that in mind for future answers. :) – Marleen Jul 31 '18 at 20:30