Search code examples
phpwordpresstags

Change the color of commas in php


Here is my code:

<?php
$posttags = get_the_tags();
if ($posttags) {
   $tagstrings = array();
   foreach($posttags as $tag) {
      $tagstrings[] = '<a href="' . get_tag_link($tag->term_id) . '" class="tag-link-' . $tag->term_id . '">' . $tag->name . '</a>';
   }
   echo implode(', ', $tagstrings);
}

// For an extra touch, use this function instead of `implode` to a better formatted string
// It will return "A, B and C" instead of "A, B, C"
function array_to_string($array, $glue = ', ', $final_glue = ' and ') {
    if (1 == count($array)) {
        return $array[0];
    }
    $last_item = array_pop($array);
    return implode($glue, $array) . $final_glue . $last_item;
}
?>

The code puts a comma after tags in WP (except the last tag). I would like to change the color of commas. How can I do it?


Solution

  • You can use something like this:

    $glue = '<span class="tagglue">,</span> ';
    

    and use that in your implode() calls (either place in your snippet).

    Then create a css declaration like:

    .tagglue {color: blue;}
    

    Implementation:

    <?php
    $posttags = get_the_tags();
    if ($posttags) {
       $tagstrings = array();
       foreach($posttags as $tag) {
          $tagstrings[] = '<a href="' . get_tag_link($tag->term_id) . '" class="tag-link-' . $tag->term_id . '">' . $tag->name . '</a>';
       }
       echo array_to_string($tagstrings);
    }
    
    // For an extra touch, use this function instead of `implode` to a better formatted string
    // It will return "A, B and C" instead of "A, B, C"
    function array_to_string($array, $glue = '<span class="tagglue">, </span>', $final_glue = ' and ') {
        if (1 == count($array)) {
            return $array[0];
        }
        $last_item = array_pop($array);
        return implode($glue, $array) . $final_glue . $last_item;
    }
    ?>
    

    I'll take this change to link several related pages on StackOverflow (that don't offer coloration):