- A+
在使用WordPress做二次开发的过程中,遇到这样的一个需求,如何获取某个分类下属的标签?那什么是某个分类的下属标签呢,我们可以这么理解,如下图:
我在WordPress后台某篇文章的编辑页面,给这篇文章选择了分类:WordPress,接着同时选择了标签:php、主题制作,这时分类(WordPress)就与标签(php、主题制作)建立了关联,利用这种关联我们实现很多种需求,最典型的是细化WordPress文章分类功能,在子分类无法达到我们的需求时,可以使用标签来细化。我只需要提供WordPress分类的id,就可以得到它关联的标签:php、主题制作。
调用函数
我们可以先在主题目录的下的functions.php添加以下函数:
function get_category_tags($args) {global $wpdb;$tags = $wpdb->get_results("SELECT DISTINCT terms2.term_id as tag_id, terms2.name as tag_name, null as tag_linkFROM$wpdb->posts as p1LEFT JOIN $wpdb->term_relationships as r1 ON p1.ID = r1.object_IDLEFT JOIN $wpdb->term_taxonomy as t1 ON r1.term_taxonomy_id = t1.term_taxonomy_idLEFT 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) {
$myCategory[$count] = get_term_by('id', $tag->tag_id, 'post_tag');
$count++;
}
}
else {
$myCategory = NULL;
}
return $myCategory;
}
函数用法
然后在其他主题文件中中,我们可以调用某个分类或某几个分类关联的标签: