0

this code returns the parent categories of the current category with links separated by '»':

echo get_category_parents( $cat, true, ' » ' );

will output:

Internet » Blogging » WordPress »

But is it possible not showing the last separated char? Like this:

Internet » Blogging » WordPress

Thanks in advance! ;)

Source: Function Reference/get category parents

  • I've found this code that work fine: $catstr = get_category_parents($cat, TRUE, ' / '); echo substr($catstr, 0, strlen($catstr) -3 ); Is it a good code? – Francesco Craparo Jan 7 '14 at 15:52
1

Another way to go about it instead of substring, would be to use implode/explode & array filter.

echo implode(" » ", array_filter( explode(" » ", get_category_parents( $cat, true, " » ") ) ) );

Breaking that down:

Start with your original string.

$string = get_category_parents( $cat, true, " » ");

Explode the string using your divider to create an array of string parts.

$string_parts = explode(" » ", $string);

Filter out any empty array parts.

$string_parts = array_filter( $string_parts );

Recombine using your divider.

$string = implode(" » ", $string_parts);

Then combine them all together to create my one line solution at the top. The code you have using substring will get the job done, but it's not the way I'd do it.

|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.