WordPress教程

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

阿里云

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

  1. function the_tags_yoowo($before = null, $sep = ', ', $after = '')
  2. {
  3.     if (null === $before) {
  4.         $before = __('Tags: ');
  5.     }
  6.     $the_tags = get_the_tag_list_yoowo($before, $sep, $after);
  7.     if (!is_wp_error($the_tags)) {
  8.         echo $the_tags;
  9.     }
  10. }
  11. function get_the_tag_list_yoowo($before = '', $sep = '', $after = '', $id = 0)
  12. {
  13.     return apply_filters('the_tags', get_the_term_list_yoowo($id, 'post_tag', $before, $sep, $after), $before, $sep, $after, $id);
  14. }
  15. function get_the_term_list_yoowo($id, $taxonomy, $before = '', $sep = '', $after = '')
  16. {
  17.     $terms = get_the_terms($id, $taxonomy);
  18.     if (is_wp_error($terms)) {
  19.         return $terms;
  20.     }
  21.     if (empty($terms)) {
  22.         return false;
  23.     }
  24.     $links = array();
  25.     foreach ($terms as $term) {
  26.         $link = get_term_link($term, $taxonomy);
  27.         if (is_wp_error($link)) {
  28.             return $link;
  29.         }
  30.         $links[] = '<a class="yoowo" href="' . esc_url($link) . '" rel="tag">' . $term->name . '</a>';//添加class属性,如果添加其他属性,也在这里更改
  31.     }
  32.     $term_links = apply_filters("term_links-{$taxonomy}", $links);
  33.     return $before . join($sep, $term_links) . $after;
  34. }
也想出现在这里?联系我们
创客主机

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

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

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

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

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

已有 175 人购买
查看演示升级 VIP立刻购买

收藏
(0)

发表回复

热销模板

Ashade - 作品展示摄影相册WordPress汉化主题
LensNews

本站承接 WordPress / PbootCMS / DedeCMS 等
系统建站、仿站、开发、定制等业务!