如何获取WordPress当前分类文章的所有标签

  • 时间:2020-05-29 14:26:07
  • 分类:网络文摘
  • 阅读:130 次

为方便读者阅读自己喜欢的内容,我们可以在wordpress分类列表页面,显示当前分类文章中添加的所有标签,以便于用户选择。下面的介绍的wordpress技巧可以帮助你实现此功能。

第一步:在wordpress主题的functions.php模板文件中添加如下函数。

  1. function get_category_tags($args) {
  2.     global $wpdb;
  3.     $tags = $wpdb->get_results
  4.     ("
  5.         SELECT DISTINCT terms2.term_id as tag_id, terms2.name as tag_name
  6.         FROM
  7.             $wpdb->posts as p1
  8.             LEFT JOIN $wpdb->term_relationships as r1 ON p1.ID = r1.object_ID
  9.             LEFT JOIN $wpdb->term_taxonomy as t1 ON r1.term_taxonomy_id = t1.term_taxonomy_id
  10.             LEFT JOIN $wpdb->terms as terms1 ON t1.term_id = terms1.term_id,
  11.             $wpdb->posts as p2
  12.             LEFT JOIN $wpdb->term_relationships as r2 ON p2.ID = r2.object_ID
  13.             LEFT JOIN $wpdb->term_taxonomy as t2 ON r2.term_taxonomy_id = t2.term_taxonomy_id
  14.             LEFT JOIN $wpdb->terms as terms2 ON t2.term_id = terms2.term_id
  15.         WHERE
  16.             t1.taxonomy = 'category' AND p1.post_status = 'publish' AND terms1.term_id IN (".$args['categories'].") AND
  17.             t2.taxonomy = 'post_tag' AND p2.post_status = 'publish'
  18.             AND p1.ID = p2.ID
  19.         ORDER by tag_name
  20.     ");
  21.     $count = 0;
  22.     if($tags) {
  23.         foreach ($tags as $tag) {
  24.             $mytag[$count] = get_term_by('id', $tag->tag_id, 'post_tag');
  25.             $count++;
  26.         }
  27.     } else {
  28.       $mytag = NULL;
  29.     }
  30.     return $mytag;
  31. }

第二步:将下面的调用输出代码,添加到当前主题的archive.php模板文件适当位置。

  1. <?php
  2.     $cat= single_cat_title('', false);
  3.     $args = array( 'categories' => get_cat_ID($cat));
  4.     $tags = get_category_tags($args);
  5.     $content .= "<ul class='cat-tag'>";
  6.     if(!emptyempty($tags)) {
  7.         foreach ($tags as $tag) {
  8.             $content .= "<li><a href=\"".get_tag_link($tag->term_id)."\">".$tag->name."</a></li>";
  9.         }
  10.     }
  11.     $content .= "</ul>";
  12.     echo $content;
  13. ?>

一般而言放到头部调用函数:

  1. <?php get_header(); ?>

下面比较合适。

最后,再适当加上样式即可:

  1. .cat-tag{
  2.     float: left;
  3.     width: 100%;
  4. }
  5. .cat-tag li a{
  6.     float: left;
  7.     margin: 0 5px;
  8. }

原文链接:http://zmingcx.com/wordpress-current-category-all-tags.html

推荐阅读:
Sum of Multiples of 3 and 5  How to Design Underground System using Several Hash Maps?  How to Remove Zero Sum Consecutive Nodes from Linked List using   Depth First Search and Breadth First Search Algorithm to Open th  Dynamic Programming (Memoization) to Sort Integers by The Power   Applicable Accounting Software For Churches  How to Balance a Binary Search Tree using Recursive Inorder Trav  Finding the Lucky Numbers in a Matrix  Factory Design Pattern in Object Oriented Design Programming  Algorithm to Find Minimum Removals to Make Valid Parentheses 
评论列表
添加评论