首页 > 解决方案 > 在php中更改逗号的颜色

问题描述

这是我的代码:

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

该代码在 WP 中的标签后放置一个逗号(最后一个标签除外)。我想更改逗号的颜色。我该怎么做?

标签: phpwordpresstagscomma

解决方案


你可以使用这样的东西:

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

并在您的implode()通话中使用它(在您的代码段中的任何地方)。

然后创建一个 CSS 声明,如:

.tagglue {color: blue;}

执行:

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

我将利用此更改链接 StackOverflow 上的几个相关页面(不提供着色):


推荐阅读