wordpress归档页面(带样式)

AI 摘要

文章介绍一种带样式的WordPress归档页制作方法,核心是采用PHP缓存机制:首次访问时生成并保存全部文章归档HTML,之后刷新直接读取缓存,避免文章较多时请求过多、加载迟缓;页面支持按年月分组和展开收缩,并在发布文章时清除缓存以更新归档。

WordPress归档页面的制作网上已经有很多了,但是各有千秋,包括我这个,也是从网上借鉴下来的代码,通过自己的优化反思,把一些细节和注意事项弄清楚了,这个归档功能有点不一样,不一样在于采取了php缓存机制,对于博客文章比较多的网站,如果采用一般的归档制作,陈列出所有文章将会出现归档页请求数太高,加载迟缓的现象。而目前这个刚好解决了这个问题,只有在第一次加载的时候才会发出所有请求,之后无论怎么刷新该页面,对数据库的影响也就等同于一般页面,甚至更少请求。

首先新建一个php文件,命名为guidang.php,然后把以下代码扔进去:

<style type="text/css"> #yuanjiao{
 font-family: Arial;
 border: 2px solid #379082;
 background-color: #fff;
 border-radius: 20px;
 padding: 30px 30px;
 width: 100%;
 }</style>
 </head>
 <body>
 <div id="yuanjiao">
 <div id="content">
 <?php /**
 * Template Name: 归档页面
 * 作者:Rookie
 * 博客://https://https:https://www.lilianhua.com/
 **/
 function qiuye_archives() {
 if( !$output = get_option('qiuye_archives') ){
 $output = '<div class="archives"><div style="text-align:center;"><a id="al_expand_collapse" href="#"">全部展开/收缩</a> <span>(点击月份伸缩)</span></div>';
 $the_query = new WP_Query( 'posts_per_page=-1&ignore_sticky_posts=1' );
 $year=0; $mon=0; $i=0; $j=0;
 while ( $the_query->have_posts() ) : $the_query->the_post();
 $year_tmp = get_the_time('Y');
 $mon_tmp = get_the_time('m');
 $y=$year; $m=$mon;
 if ($mon != $mon_tmp && $mon > 0) $output .= '</ul></li>';
 if ($year != $year_tmp && $year > 0) $output .= '</ul>';
 if ($year != $year_tmp) {
 $year = $year_tmp;
 $output .= '<h3 class="al_year">'. $year .'年</h3><ul class="al_mon_list">';}
 if ($mon != $mon_tmp) {
 $mon = $mon_tmp;
 $output .= '<li><span class="al_mon">'. $mon .' 月</span><ul class="al_post_list">';}
 $output .= '<li class="atitle"><span class="ttime">'. get_the_time('m月d日: ') .'</span><a class="tttile" href="'. get_permalink() .'">'. get_the_title() .'</a> <span class="ttcom">(<a title="'. get_comments_number('0', '1', '%') .'条评论">'. get_comments_number('0', '1', '%') .'</a>)</span></li>';
 endwhile;wp_reset_postdata();
 $output .= '</ul></li></ul></div>';
 update_option('qiuye_archives', $output);}
 echo $output;}
 function clear_zal_cache() {
 update_option('qiuye_archives', '');}
 add_action('save_post', 'clear_zal_cache');
 ?>
 <?php /*清除缓存动作clear_zal_cache();*/ ?><?php qiuye_archives(); ?>
 <script>
 jQuery(document).ready(function($){
 (function(){
 $('#al_expand_collapse,.archives span.al_mon').css({cursor:"s-resize"});
 $('.archives span.al_mon').each(function(){
 var num=$(this).next().children('li').size();
 var text=$(this).text();
 $(this).html(text+'<span> ( '+num+' 篇文章 )</span>');});
 var $al_post_list=$('.archives ul.al_post_list'),
 $al_post_list_f=$('.archives ul.al_post_list:first');
 $al_post_list.show(1,function(){
 $al_post_list_f.show();});
 $('.archives span.al_mon').click(function(){
 $(this).next().slideToggle(400);
 return false;});
 $(function() {
 $("#al_expand_collapse").click(function(event) {
 $al_post_list.toggle(400);});});})();});
 </script>
 </div>
</div>

评论