Seemingly Simple ForEach Loop Problem..
Posted: Thu Jul 01, 2010 3:16 pm
Hello everyone. Im working on a Wordpress site and ran into a problem trying to display some information in a foreach loop. I have very remedial PHP skills and have searched far and wide for the answer and cant seem to get it. I found a way to customize the way my categories are displayed and found this chunk of code online and it works perfectly.
The only problem is the trailing comma at the end of the loop. It displays like 'Categories: Category 1, Category2, Category 3,'.
I got the closest using substr but it deleted all of the comma's, not just the last one. Here is the code I used for that:
All I want is for this to display 'Categories: Category 1, Category 2, Category 3' like the regular wordpress category function does. Any help is very very much appreciated!
Code: Select all
<?php
foreach((get_the_category()) as $childcat)
{
if (cat_is_ancestor_of(10, $childcat))
{
echo '<a href="'.get_category_link($childcat->cat_ID).'">'; echo $childcat->cat_name . '</a>' . ', ';
}
}
?>
I got the closest using substr but it deleted all of the comma's, not just the last one. Here is the code I used for that:
Code: Select all
<?php
foreach((get_the_category()) as $childcat)
{
if (cat_is_ancestor_of(10, $childcat))
{
$str = '<a href="'.get_category_link($childcat->cat_ID).'">' . $childcat->cat_name . '</a>' . ', ';
substr($str, 0, -2); echo $str;
}
} ?>