WordPress分类列表调用该分类置顶文章

制作wordpress有主题模板的时候,需要实现这样的功能:调用wordpress网站某个分类下文章的关联标签…

制作wordpress有主题模板的时候,需要实现这样的功能:调用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
function get_category_tags($args) {
	global $wpdb;
	$tags = $wpdb->get_results
		("
            SELECT DISTINCT terms2.term_id as tag_id, terms2.name as tag_name
            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 terms1.term_id IN (".$args['categories'].") AND
                t2.taxonomy = 'post_tag' AND p2.post_status = 'publish'
                AND p1.ID = p2.ID
            ORDER by tag_name
        ");
        $count = 0;
 
        if($tags) {
			foreach ($tags as $tag) {
				$mytag[$count] = get_term_by('id', $tag->tag_id, 'post_tag');
				$count++;
			}
        }
        else {
			$mytag = NULL;
        }       
        return $mytag;
}

在要显示分类关联标签的主题文件添加以下调用代码:

1
2
3
4
5
6
7
8
9
10
<?php 
	$args = array( 'categories' => '1,2');
	$tags = get_category_tags($args);
	if(!empty($tags)) {
		foreach ($tags as $tag) {
			$content .= "<a href="".get_tag_link($tag->term_id)."">".$tag->name."</a>";
		}
	}
	echo $content;
?>

添加多个分类ID就调用多个分类的关联标签

代码来自:露兜博客

类别:WordPress教程

本文收集自互联网,转载请注明来源。
如有侵权,请联系 wper_net@163.com 删除。

评论 (0)COMMENT

登录 账号发表你的看法,还没有账号?立即免费 注册