如何在Popular Posts插件中添加缩略图
2012/04/25
相信还有很多人使用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="' . $src . '"><img src="' . $imgpath . '" alt="'. $title .'" /></a> <a href="' . $src . '">' . $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文件中即可。




