tags:

views:

39

answers:

3

Hey all,

I am using the foreach function to get all the categories for a WordPress site and need a way to adjust the output if there is another tag, to include dynamic CSS.

Basically, if I have only one tag I need the code output to look like this:

.category-wordpress #wordpress { background: #FFFFFF; color: #232323; text-decoration: none; }

and if there's more than one tag like this:

.category-wordpress #wordpress, .category-html #html { background: #FFFFFF; color: #232323; text-decoration: none; }

The problem is with the comma between declarations. How can I change this code so a comma is only included if there is another category to include?

if (is_category()) { 

$css_cats = "<style type='text/css'>";

 //get all blog categories
 $categories = get_categories('title_li=&orderby=name&hide_empty=0');

 if ($categories) {

  foreach($categories as $category) {

   $css_cats .= ".category-".$category->category_nicename." #".$category->category_nicename.", ";

  }

 } 

$css_cats .= "{ background: #FFFFFF; color: #232323; text-decoration: none; }";

$css_cats .= "</style>";

echo $css_cats;

}

This code is outputting a comma at the end of the last declaration like this:

.category-wordpress #wordpress, .category-html #html, { background: #FFFFFF; color: #232323; text-decoration: none; }

so the CSS breaks.

I can change the code so it outputs the CSS declarations individually like this:

.category-wordpress #wordpress { background: #FFFFFF; color: #232323; text-decoration: none; }
.category-html #html { background: #FFFFFF; color: #232323; text-decoration: none; }

but surely there's a better way?

Any help is greatly appreciated.

Cheers,

James

A: 

After foreach do for example

 $css_cats = substr($css_cats,0,-2);
Mchl
A: 
  $first = true;

  foreach($categories as $category) {
     if($first)
        $first = false;
     else
        $css_cats .= ', ';

     $css_cats .= ".category-".$category->category_nicename." #".$category->category_nicename;
  }
Krevan
You are a legend! That's exactly what I needed.Many thanks.
+3  A: 

Here is another way:

$cats_arr = array();

foreach($categories as $category) {
    $cats_arr[] = ".category-".$category->category_nicename." #".$category->category_nicename;  
}

$css_cats .= implode(',', $cats_arr);

References: implode()

Felix Kling