在使用WordPress系统写文章时,有时候我们需要在文章中插入分类目录下的标签,而且需要的是选取标签、随机排列标签。完成这一步,需要以下代码。
首先需要创建一个函数,选取分类目录下的标签,并让其随机排列:
- / **
- * WordPress系统随机获取某个分类中的标签
- * /
- 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++;
- }
- shuffle( $mytag ); // 把数组中的元素按随机顺序重新排序
- } else {
- $mytag = NULL;
- }
- return $mytag; // 返回数组
- }
之后,在博文或者需要引入标签的地方调用该函数:
- $cat= single_cat_title( '', false );
- $args = array( 'categories' => get_cat_ID( $cat ) ); // 获取分类ID
- $tags = get_category_tags( $args ); // 获取该ID下的标签
- $content .= "<ul>";
- if( !empty( $tags ) && ($tags != NULL) ) { // 如果有标签
- $i = 0;
- foreach ( $tags as $tag ) {
- $i++;
- if( $i <= 20 ) { // 控制标签数量
- $content .= "<li><a href=\"".get_tag_link($tag->term_id)."\" target='_blank'>".$tag->name."</a></li>"; // 获取标签名称和链接
- }
- }
- $content .= "</ul>";
- echo $content;
- } // 输出标签
大功告成,试一下吧!
代码已分享在这里:pan.baidu.com/s/1tfTRC50oSAVYEC-nAKYmLw 密码: iqtm