众所周知,我们可以使用the_tags()函数进行输出一篇文章的所有标签。
但是,开发路上什么都会碰上,例如给a标签添加一个class属性,这是自带的参数所做不到的,那么我们如何解决呢?
下面我们以给输出的a标签添加一个yoowo的class属性作为例子:
首先在functions.php中添加下面的代码:
/* WordPress自定义输出文章标签
* Author: yoowo222
* CreateTime: 2020/9/19 下午10:07:53
* LastEditor: yoowo222
* ModifyTime: 2020/9/19 下午10:07:53
* Description: WordPress custom output article label
*/
function the_tags_yoowo($before = null, $sep = ', ', $after = '')
{
if (null === $before) {
$before = __('Tags: ');
}
$the_tags = get_the_tag_list_yoowo($before, $sep, $after);
if (!is_wp_error($the_tags)) {
echo $the_tags;
}
}
function get_the_tag_list_yoowo($before = '', $sep = '', $after = '', $id = 0)
{
return apply_filters('the_tags', get_the_term_list_yoowo($id, 'post_tag', $before, $sep, $after), $before, $sep, $after, $id);
}
function get_the_term_list_yoowo($id, $taxonomy, $before = '', $sep = '', $after = '')
{
$terms = get_the_terms($id, $taxonomy);
if (is_wp_error($terms)) {
return $terms;
}
if (empty($terms)) {
return false;
}
$links = array();
foreach ($terms as $term) {
$link = get_term_link($term, $taxonomy);
if (is_wp_error($link)) {
return $link;
}
$links[] = '' . $term->name . '';//添加class属性,如果添加其他属性,也在这里更改
}
$term_links = apply_filters("term_links-{$taxonomy}", $links);
return $before . join($sep, $term_links) . $after;
}
添加的地方已经注释了,你也可以随便自定义它,直到达成想要的效果。
最后就是前台调用了,调用方法是:
当然,这支持the_tags()的所有参数。