WordPress免插件仅代码实现文章归档模板

首页 论坛 分类论坛 BlogWall优化笔记 WordPress免插件仅代码实现文章归档模板

标签: 

正在查看 0 条回复
  • 作者
    帖子
    • #4992
      管理员
      管理员

      这几天空了就完善下网站,给网站增加了文章归档页面,列表展示本站所有文章。主要参考的还是zww大神的文章,这篇教程多年来被广泛采用。在大神的基础上,我稍微修改了下。以下代码为本站修改后的版本。

      第一步:在主题文件 functions.php中添加下面的代码:

      /* Archives list */
      function blogwall_archives_list() {
      if( !$output = get_option(‘blogwall_db_cache_archives_list’) ){
      $output = ‘<div id=”archives”>’;
      $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> </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 .’ 月 </span><ul class=”al_post_list”>’; //输出月份
      $output .= $posts; //输出 posts
      $output .= ‘</ul></li>’;
      }
      $output .= ‘</ul>’;
      }

      $output .= ‘</div>’;
      update_option(‘blogwall_db_cache_archives_list’, $output);
      }
      echo $output;
      }
      function clear_db_cache_archives_list() {
      update_option(‘blogwall_db_cache_archives_list’, ”); // 清空 blogwall_archives_list
      }
      add_action(‘save_post’, ‘clear_db_cache_archives_list’); // 新发表文章/修改文章时

      2. 复制一份主题的 page.php 更名为 archives.php,然后在最顶端加入:

      <?php
      /*
      Template Name: Archives
      */
      ?>

      在 archives.php 找到类似 <?php content(); ?>,在其下面加入如下代码

      <?php blogwall_archives_list(); ?>

      然后新建页面(如叫:归档),选择模版为 Archives

      本站归档页面展示

正在查看 0 条回复
  • 哎呀,回复话题必需登录。