今天小編就為大家分享一篇關于wordpress自定義標簽云與隨機獲取標簽的方法詳解,小編覺得內容挺不錯的,現在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧。
wp_tag_cloud() 函數的作用是用來標簽云的,可以根據每個標簽所關聯的文章次數來定義字體大小、標簽排序等屬性。從 2.8 版本開始,添加了 分類法(taxonomy)參數,這就意味著,除了 標簽(tags)以外,還可以將 分類(Categories) 或其他 自定義分類法(Custom Taxonomies)作為“云”顯示。
用法:
<?php wp_tag_cloud( $args ); ?>
默認用法:
<?php $args = array( 'smallest' => 8, 'largest' => 22, 'unit' => 'pt', 'number' => 45, 'format' => 'flat', 'separator' => "/n", 'orderby' => 'name', 'order' => 'ASC', 'exclude' => null, 'include' => null, 'topic_count_text_callback' => default_topic_count_text, 'link' => 'view', 'taxonomy' => 'post_tag', 'echo' => true, 'child_of' => null(see Note!) ); ?>
注: child_of 不是一個直接的 wp_tag_cloud 數組的鍵(Key),但由于這個函數使用 wp_parse_args() 和 get_terms() ,你可以通過 get_terms() 使用所有的數組鍵。
默認情況下的輸出內容:
smallest —— 最小的標簽(使用次數最少)顯示大小為8
largest ——最大的標簽(使用次數最多)顯示大小為22
unit —— 最大值最小值的單位為'pt'
number —— 至多顯示45個標簽
format —— 以平面形式顯示所有標簽(標簽之間用空格隔開)
separator —— 顯示標簽之間的空格
orderby —— 按名稱為標簽排序
order —— 以升序排列
exclude —— 不排除任何標簽
include —— 包括所有標簽
topic_count_text_callback —— 使用函數 default_topic_count_text
link —— 可視
taxonomy —— 用文章的標簽作為云基礎
echo —— 輸出結果
但由于該方法把樣式集合到了里面,使用起來不怎么友好,如果想自定義讀取標簽并修改展示樣式該怎么做呢,那也是非常簡單的,看代碼實例,這里根據get_tags來獲?。?/p>
- $html = '<ul class="post_tags">';
- foreach (get_tags( array('number' => 50, 'orderby' => 'count', 'order' => 'DESC', 'hide_empty' => false) ) as $tag){
- $color = dechex(rand(0,16777215));
- $tag_link = get_tag_link($tag->term_id);
- $html .= "<li><a href='{$tag_link}' title='{$tag->name} Tag' class='{$tag->slug}' style='color:#{$color}'>";
- $html .= "{$tag->name} ({$tag->count})</a></li>";
- }
- $html .= '</ul>';
- echo $html;
如果要求隨機獲取標簽在首頁顯示,那可以使用以下代碼,但這種做法貌似不利于seo,可得慎重使用。
- //獲取隨機標簽
- function get_rand_tags()
- {
- global $post, $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 20";
- $related_posts = $wpdb->get_results($sql);
- $html = '<ul class="post_tags">';
- foreach($related_posts as $tag)
- {
- $color = dechex(rand(0,16777215));
- $tag_link = get_tag_link($tag->term_id);
- $html .= "<li><a href='{$tag_link}' target='_blank' title='{$tag->name} Tag' class='{$tag->slug}' style='color:#{$color}'>";
- $html .= "{$tag->name} ({$tag->count})</a></li>";
- }
- $html .= '</ul>';
- echo $html;
- }
獲取隨機標簽用get_tags函數怎么變化參數都是沒法獲取到的(反正我是獲取不到,歡迎大神留言指導),結果最后就用的sql連接表查詢就搞出來了。
新聞熱點
疑難解答
圖片精選