大挖在开发仿亿欧网wordpress cms主题模版内容资讯类分类页面时需要调用分类下的所有标签实现分类热门tags的效果,其实很简单,只要添加以下代码就可以实现,然后通过自动分类id识别来自动调用分类下的热门标签现在给大家分享出来,可以添加到各分类页面,用来增强seo的标签关联,标签对seo的内链池有着很好的优化辅助作用
我们可以先在主题目录的下的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 |
function wa_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 11 12 13 14 15 16 17 |
// 12,13是分类ID,多个用半角逗号隔开 $args = array( 'categories' => '12,13'); // 调用上面定义的函数,来获取ID为12,13的分类的关联标签 $tags = wa_get_category_tags($args); // 输出我们获取到的关联标签,以列表形式打印 $content .= "<ul>"; if(!empty($tags)) { foreach ($tags as $tag) { $content .= "<li><a href="".get_tag_link($tag->term_id)."">".$tag->name."</a></li>"; } } $content .= "</ul>"; echo $content; |