相信還有很多人使用 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 文件中即可。