折腾为王
我探索过很多小众功能,有实用的、也有毫无用处的。但文章归档页一直隐蔽在角落里,未曾重视过。想赶在2022的尾巴上,整个不一样的归档页出来,好在有需求就有检索目标,有目标就有一定会有雏形,方案代码出自 @zwwooooo 的《WordPress 归档页面模板2014版》,样式根据自己的需求重写了。最终效果如图:
有趣的点
在实际制作归档页的时候,我发现三个有意思的点:
- 原本并不知道JQuery干嘛用的,半天没效果,因此我在 header.php 里注释掉,直接放入归档页居然生效;
- 刚开始重写样式不产生变动,非缓存问题,直接写进函数里就有效。等重写完所有的效果,再次放入样式表里生效;
- jQuery 库不需要引入第三方,用 WP 自带的即可。
归档代码
function zww_archives_list() { if( !$output = get_option('zww_db_cache_archives_list') ){ $output = '<div id="archives"><p><a id="al_expand_collapse" href="#">全部展开/收缩</a> <em>(注: 点击月份可以展开)</em></p>'; $args = array( 'post_type' => 'post', //如果你有多个 post type,可以这样 array('post', 'product', 'news') 'posts_per_page' => -1, //全部 posts 'ignore_sticky_posts' => 1 //忽略 sticky posts ); $the_query = new WP_Query( $args ); $posts_rebuild = array(); $year = $mon = 0; while ( $the_query->have_posts() ) : $the_query->the_post(); $post_year = get_the_time('Y'); $post_mon = get_the_time('m'); $post_day = get_the_time('d'); if ($year != $post_year) $year = $post_year; if ($mon != $post_mon) $mon = $post_mon; $posts_rebuild[$year][$mon][] = '<li>'. get_the_time('d日: ') .'<a href="'. get_permalink() .'">'. get_the_title() .'</a> <em>('. get_comments_number('0', '1', '%') .')</em></li>'; endwhile; wp_reset_postdata(); foreach ($posts_rebuild as $key_y => $y) { $output .= '<h3 class="al_year">'. $key_y .' 年</h3><ul class="al_mon_list">'; //输出年份 foreach ($y as $key_m => $m) { $posts = ''; $i = 0; foreach ($m as $p) { ++$i; $posts .= $p; } $output .= '<li><span class="al_mon">'. $key_m .' 月 <em> ( '. $i .' 篇文章 )</em></span><ul class="al_post_list">'; //输出月份 $output .= $posts; //输出 posts $output .= '</ul></li>'; } $output .= '</ul>'; } $output .= '</div>'; update_option('zww_db_cache_archives_list', $output); } echo $output; } function clear_db_cache_archives_list() { update_option('zww_db_cache_archives_list', ''); // 清空 zww_archives_list } add_action('save_post', 'clear_db_cache_archives_list'); // 新发表文章/修改文章时
jQuery代码
(function ($, window) { $(function() { var $a = $('#archives'), $m = $('.al_mon', $a), $l = $('.al_post_list', $a), $l_f = $('.al_post_list:first', $a); $l.hide(); $l_f.show(); $m.css('cursor', 's-resize').on('click', function(){ $(this).next().slideToggle(400); }); var animate = function(index, status, s) { if (index > $l.length) { return; } if (status == 'up') { $l.eq(index).slideUp(s, function() { animate(index+1, status, (s-10<1)?0:s-10); }); } else { $l.eq(index).slideDown(s, function() { animate(index+1, status, (s-10<1)?0:s-10); }); } }; $('#al_expand_collapse').on('click', function(e){ e.preventDefault(); if ( $(this).data('s') ) { $(this).data('s', ''); animate(0, 'up', 100); } else { $(this).data('s', 1); animate(0, 'down', 100); } }); }); })(jQuery, window);