不用插件制作WordPress存档列表页面
WordPress有很多优秀的Archives存档页面插件,如我之前一直用的Clean Archives Reloaded。在我看来,所有的网站都应该有Archives存档页面,它可以方便你的读者快速浏览您的网站,找到他们所感兴趣的东东。而且,存档页面对于SEO也是非常友好的。不过,装载太多的插件对于网站访问速度会有一定影响,所以,我们应该尝试着不用或少用插件。今天,我来谈谈如何不用插件,制作Archives存档列表页面。
很简单的几步,不用修改style.css,能保证主题兼容性。
第一步,复制当前theme的 page.php 文件,重命名为 archives.php,打开该文件,作如下修改。
在文件开头添加:
<?php /* Template Name: Archives */ ?>
在<?php the_content(); ?> 后添加:
<?php post_archive(); ?>
第二步,复制以下代码到 functions.php
function post_archive()
{
global $month, $wpdb;
$now = current_time('mysql');
$arcresults = $wpdb->get_results("SELECT DISTINCT YEAR(post_date) AS year, MONTH(post_date) AS month, count(ID) as posts FROM " . $wpdb->posts . " WHERE post_date <'" . $now . "' AND post_status='publish’ AND post_type=’post’ AND post_password=” GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC");
if ($arcresults) {
foreach ($arcresults as $arcresult) {
$url = get_month_link($arcresult->year, $arcresult->month);
$text = sprintf('%s %d', $month[zeroise($arcresult->month,2)], $arcresult->year);
echo get_archives_link($url, $text, '','<h3>','</h3>');
$thismonth = zeroise($arcresult->month,2);
$thisyear = $arcresult->year;
$arcresults2 = $wpdb->get_results("SELECT ID, post_date, post_title, comment_status FROM " . $wpdb->posts . " WHERE post_date LIKE '$thisyear-$thismonth-%' AND post_status='publish’ AND post_type=’post’ AND post_password=” ORDER BY post_date DESC");
if ($arcresults2) {
echo "<ul class=\"postspermonth\">\n";
foreach ($arcresults2 as $arcresult2) {
if ($arcresult2->post_date != '0000-00-00 00:00:00') {
$url = get_permalink($arcresult2->ID);
$arc_title = $arcresult2->post_title;
if ($arc_title) $text = strip_tags($arc_title);
else $text = $arcresult2->ID;
echo "<li>".get_archives_link($url, $text, '');
$comments = mysql_query("SELECT * FROM " . $wpdb->comments . " WHERE comment_post_ID=" . $arcresult2->ID);
$comments_count = mysql_num_rows($comments);
if ($arcresult2->comment_status == "open" OR $comments_count > 0) echo ' ('.$comments_count.')';
echo "</li>\n";
}
}
echo "</ul>\n";
}
}
}
}
?>
第三步,后台新建一个page, 在“页面模板(page template)”中选择“Archives”。
That’s all!
相关阅读: