WordPress系统自带的get_tags()函数调用,不能获取随机标签。

WordPress
下面这个通过查询数据库的方法,可以实现随机标签的获取:
/* random tags */
        global $wpdb;
        $sql = "SELECT * FROM {$wpdb->prefix}terms wt INNER JOIN {$wpdb->prefix}term_taxonomy wtt on wt.term_id=wtt.term_id where wtt.taxonomy='post_tag' ORDER BY RAND() LIMIT 21";
        $tags = $wpdb->get_results($sql);
        // $tags = get_tags(array(
        //     "number" => $limit,
        //     "ORDER BY"=>"RAND()",
        //     "order" => "desc",
        // ));
        foreach($tags as $tag){
            $count = intval( $tag->count );
            $name = apply_filters( 'the_title', $tag->name );
            $class = ( $count > 5 ) ? 'tag-item hot' : 'tag-item';
            echo '<a href="'. esc_attr( get_tag_link( $tag->term_id ) ) .'" class="'. $class .'" title="浏览和' . $name . '有关的文章"><span>' . $name . '</span></a>';
        }
以上代码实现从WordPress数据库中随机获取21个标题,简单好用。
一般直接查询数据库,都是比较快的,如果网站页面经过静态化处理,就不用担心速度的问题了。















