相信還有很多人使用 Popular Posts 熱門文章外掛來在 WordPress 實現熱門日誌的。而在熱門文章前加一個縮圖是不是很酷呢?本文將實現這個功能。本文設計的知識點包括一些 phpPHP, MySQL, 和 WordPress 。
文章背景需要
- Popularity Contest 外掛. 這個 WordPress 外掛來自 Alex King. 可以透過 WordPress 後臺外掛找到。
- TimThumb Script. 需要這個 Tim McDaniels 和 Darren Hoytscript 建立的程式碼。
- 隨便一個 WordPress 主題. 這個主題將會被修改,做好備份。
步驟 1: 修改目錄結構
先啟用 Popularity Contest 外掛。 在 wp-content 資料夾下, 建立資料夾 tt-script. 在 tt-script 資料夾下, 把 timbthumb.php 貼上進去. 仍然在 tt-script 資料夾下建立資料夾 cache 。
步驟 2: 設定預設影像
把預設影像放到 tt-script 資料夾下. 本教程中設定的影像大小 16 pixels X 16 pixels,檔名為 default.png. 支援所有影像格式.
步驟 3: 函式頁面修改
在主題資料夾下,開啟 function.php 檔案, 有兩個函式需要貼上進來。第一個是抓去第一個影像的。
/**
* Capture the first image from the post.
* @global object $post
* @global object $posts
* @return string
*/
function theme_function_capture_first_image($p=null) {
$firstImg = '';
if (empty($p)) {
global $post, $posts;
$firstImg = '';
ob_start(); ob_end_clean();
$output = preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $post->post_content, $matches);
$firstImg = $matches[1][0];
} else {
$output = preg_match_all('/<img.+src=['"]([^'"]+)['"].*>/i', $p->post_content, $matches);
$firstImg = $matches[1][0];
}
return $firstImg;
}
第二個函式是顯示熱門日誌的,可以使用 Alex King』s Popularity Plugin 函式.
/**
* Renders the list of most popular posts together with icons.
* @global object $akpc
*/
function theme_function_popular_posts() {
if (function_exists('akpc_most_popular')) {
global $akpc;
$posts = $akpc->get_top_ranked_posts(5);
if ($posts)
// Your preferred default icon url.
$default = get_option('siteurl'). '/wp-content/tt-script/default.png';
$scrp = get_option('siteurl'). '/wp-content/tt-script/timthumb.php?';
echo '<ul>';
foreach ($posts as $post) {
$img = theme_function_capture_first_image(get_post($post->ID))
$src = get_permalink($post->ID);
$title = $post->post_title;
$imgpath = '';
if (empty($img)) {
$imgpath = $default;
} else {
$imgpath = $srcp . 'src=' . $img . '&w=16&h=16&zc=1';
}
echo '<li><a href="'%20.%20$src%20.%20'"><img src="'%20.%20%20$imgpath%20.%20'" alt="'. $title .'" /></a> <a href="'%20.%20$src%20.%20'">' . $title .'</a></li>';
}
echo '</ul>';
} else {
print('<p>There are no popular posts shown.</p>');
}
} else {
echo '<p>Please install the Alex King's Popularity Contest Plugin.</p>';
}
}
把程式碼放到邊欄
現在已經建立了兩個必須的函式,剩下的事情就比較少。開啟主題資料夾下的 sidebar.php 檔案,貼上如下程式碼:
<li> <h2>Most Popular</h2> <?php theme_function_popular_posts(); ?> </li>
有時我喜歡把它放在小工具內:
<div> <h2>Most Popular</h2> <div> <?php theme_function_popular_posts(); ?> </div> </div>
還有一種方法,也會顯示帶有縮圖的日誌,假設你想讓它真的工具化。使用下面程式碼:
function theme_widget_popular_posts_icons($args) {
extract($args, EXTR_SKIP);
echo $before_widget . "n";
echo $before_title . 'Most Popular' . $after_title . "n";
theme_function_popular_posts();
echo $after_widget . "n";
}
register_sidebar_widget('Your Theme Name Feedburner Subscription', 'theme_widget_popular_posts_icons');
把這段程式碼複製到 function.php 檔案中即可。