WordPress 自定义格式输出文章标签

WordPress 自定义格式输出文章标签

众所周知,我们可以使用 the_tags()函数进行输出一篇文章的所有标签。但是,开发路上什么都会碰上,例如给 a 标签添加一个 class 属性,这是自带的参数所做不到的,那么我们如何解决呢?下面我们以给输出的 a 标签添加一个 yoowo 的 class 属性作为例子:首先在 functions.php 中添加下面的代码:

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[] = '<a class="yoowo" href="' . esc_url($link) . '" rel="tag">' . $term->name . '</a>';//添加class属性,如果添加其他属性,也在这里更改
    }
    $term_links = apply_filters("term_links-{$taxonomy}", $links);
    return $before . join($sep, $term_links) . $after;
}

添加的地方已经注释了,你也可以随便自定义它,直到达成想要的效果。

最后就是前台调用了,调用方法是:

<?php the_tags_yoowo('', '', ''); ?>

当然,这支持 the_tags() 的所有参数。

温馨提示:本文最后更新于2022-05-12 20:33:19,某些文章具有时效性,若有错误或已失效,请在下方留言或联系乡野博文
您阅读这篇文章共花了: 0小时00分00秒
-----本页内容已结束,喜欢请分享!-----
© 版权声明
THE END
喜欢本站内容,请点【点赞】【分享】和【收藏】~
点赞14 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容