有時候我們希望在側欄放更多內容,但是容易讓側欄顯得過長。網上比較常見的做法是,用 Tab 選項卡的形式將多個小工具合并到一起,例如熱門文章、最新文章、隨機文章等等,這樣同樣的空間包含的內容更多,用戶體驗也增強不少。
下面講講具體的實現步驟,主要分成三塊內容:PHP部分、JQuery切換實現以及 CSS樣式。
PHP部分
在 Tab 選項卡中有一欄是熱評文章,它根據文章的評論數來排列熱門文章,WordPress 默認并沒有提供該功能。所以需要自己來實現,將以下代碼放到主題目錄下的 function.php 文件中:
// 獲得熱評文章
function wpex_get_most_viewed($posts_num = 10, $days = 60) {
global $wpdb;
$sql = "SELECT ID , post_title , comment_count FROM $wpdb->posts
WHERE post_type = 'post' AND post_status = 'publish'
AND TO_DAYS(now()) - TO_DAYS(post_date) < $days
ORDER BY comment_count DESC LIMIT 0 , $posts_num ";
$posts = $wpdb->get_results($sql);
$output = "";
foreach ($posts as $post) {
$output .= "<li><a href= \"".get_permalink($post->ID)."\" rel=\"bookmark\" title=\"".$post->post_title." (".$post->comment_count."條評論)\" >". wp_trim_words($post->post_title, 30)."</a></li>";
}
echo $output;
}
wpex_get_most_viewed函數用來獲取最近N天的評論數最多的M篇文章。
接下來,將下面的代碼放到主題目錄下的 sidebar.php 文件中,這段代碼主要描述了側欄小工具的結構:
<div class="sidebar-box tabber-widget">
<div class="tabber-title">
<ul class="tabnav clr">
<li class="selected">最新文章</li>
<li class="">熱評文章</li>
<li class="">隨機文章</li>
</ul>
</div>
<div class="tabber-content">
<ul><?php $myposts = get_posts('numberposts=10&offset=0');foreach($myposts as $post): ?>
<li><a href="<?php the_permalink(); ?>" rel="bookmark" title="詳細閱讀 <?php the_title_attribute(); ?>"><?php echo wp_trim_words($post->post_title,30); ?></a></li>
<?php endforeach; ?></ul>
<ul class="hide"><?php wpex_get_most_viewed(10, 180); ?></ul>
<ul class="hide"><?php $myposts = get_posts('numberposts=10&orderby=rand');foreach($myposts as $post): ?>
<li><a href="<?php the_permalink(); ?>" rel="bookmark" title="詳細閱讀 <?php the_title_attribute(); ?>"><?php echo wp_trim_words($post->post_title,30); ?></a></li>
<?php endforeach; ?></ul>
</div>
</div>
JQuery 切換實現
Tab 選項卡的最重要的一個功能點是,點擊標簽可以切換到對應的內容。我們可以選擇用JQuery來實現切換的效果,這樣代碼會顯得很干凈和簡單。
將以下的代碼放到你自己的某個 js 文件中:
jQuery(function($) {
$('.tabber-title li').click(function() {
var $cur_tab = $(this);
var $tabber = $cur_tab.parents('.tabber-widget');
$cur_tab.addClass("selected")
.siblings().removeClass("selected");
$tabber.find('.tabber-content ul').slideUp('fast')
.eq($tabber.find('.tabber-title li').index(this)).slideDown('fast');
});});
CSS 樣式
現在我們要給 Tab 選項卡披上一件漂亮的衣服,這件衣服可能并不適合每個人,所以需要根據自己的情況調整改進。
將以下代碼放到主題目錄下的 style.css 文件中:
/* Tabber widget */
.tabber-title {margin:0 0 15px}
.tabnav { color: #000; font-weight: bold; font-size: 14px; border-bottom: 1px solid #ddd; }
.tabnav li {
float:left;
width:86px;
height:30px;
line-height:30px;
border:1px solid #ddd;
border-bottom:none;
text-align:center;
cursor:pointer;
margin-left:10px;
color: #666;
}
.tabnav .selected { cursor:default; background: #efefef; color: #000; }
.tabber-content .hide {display:none;}
.tabber-content ul {overflow:hidden;list-style:none}
.tabber-content li {overflow:hidden;padding-bottom: 2px;}
.tabber-content {padding: 0 10px;}
到此就大功告成了,你也可以舉一反三,將其它內容放到 Tab 選項卡中。