获取wordpress文章标签关联的分类

WordPress教程 2984

前面介绍的《WordPress获取某分类下文章使用过的标签》满足了获取分类关联标签的需求,现在反过来要获取标签关联的分类怎么办?既然可以通过分类获取关联标签,那么也可以通过标签获取关键的分类。通过对前面的函数代码进行简单的修改就可以实现该功能效果。

functions.php文件代码:

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

调用代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
    // 12,13是标签ID,多个用半角逗号隔开
    $args = array( 'tags' => '12,13');
    // 调用上面定义的函数,来获取ID为12,13的标签的关联分类
    $categories = ludou_get_tag_categories($args);
    // 输出我们获取到的关联分类,以列表形式打印
    $content .= "<ul>";
    if(!empty($categories)) {
      foreach ($categories as $category) {
        $content .= "<li><a href=\"".get_category_link( $category->term_id )."\">".$category->name."</a></li>";
      }
    }
    $content .= "</ul>";
    echo $content;
?>

代码来自:露兜博客

精品推荐: