在前面的文章中,我们介绍过WordPress CMS主题如何实现彩色标签云效果,这个是从全站文章中获取wordpress文章的标签。有时,我们可能有这样的需求:我们开发的wordpress CMS主题需要按照分类来获取当前分类下的文章的标签,不同的分类调用不的tag标签。如:wordpress CMS主题首页调用不同分类时调用该分类的tag标签、文章分类列表页调用当前分类下的tag标签等。
第一步:在WordPress主题的functions.php主函数文件中添加如下代码:
//获取分类下的文章标签
function ludou_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;
}
这个代码就不做过多解释了,这里用到了mysql数据为的LEFT JOIN左连接查询进行多表查询,然后把查询到的结果放到$mytag数组中,然后返回这个数组。该函数的参数是一个数组。
2:获取分类ID:
如果是分类页面,获取当前分类ID,然后把该ID放到数组中:
$cid = get_query_var('cat'); //获取当前分类ID
$args = array( 'categories' => array($cid) ); //把ID放到数组中
如果是wordpress主题首页,可以直接把分类的id放到一个数组中:
$args = array( 'categories' => array(2,5,8,355) );
3:获取wordpress分类的tag标签:
$tags = ludou_get_category_tags($args);// 来获取指定分类的文章标签
shuffle($tags); //打乱数组,让它随机
// 输出我们获取到的关联标签,以列表形式打印出来
$content .= "";
";
$i = 0;
if(!empty($tags)) {
foreach ($tags as $tag) {
if($i<35){ //限制个数,根据自己的需要修改数
$content .= "
";
}
$i++;
}
}
$content .= "
echo $content;
这样,我们就为wordpress CMS主题实现了按分类来调用当前分类下的文章tag标签的功能。