Page 1 of 1

Seemingly Simple ForEach Loop Problem..

Posted: Thu Jul 01, 2010 3:16 pm
by jjk215
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.

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>' . ', '; 
        }
}
 ?>
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:

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;
	}
	
} ?>
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!

Re: Seemingly Simple ForEach Loop Problem..

Posted: Thu Jul 01, 2010 3:36 pm
by AbraCadaver
I might do it like this:

Code: Select all

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

Re: Seemingly Simple ForEach Loop Problem..

Posted: Thu Jul 01, 2010 4:51 pm
by jjk215
You're the man! :drunk: