给Twenty Twelve主题添加归档页面

Twenty Twelve主题更新后依然没有更好的文章标题列表形式,所以制作了个归档页面,这里感谢灵尘居lingchenzi.com提供的代码帮助,感谢~!下图样式

文章归档

具体实现方法如下!

方案一:

  1. 复制一份主题的 page.php 更名为 archives.php,然后在最顶端加入:
<?php
/*
Template Name: archives
*/
?>

2.复制模版内文件content-page.php,重命名content-archives.php在 “entry-content”>后加入如下归档列表输出代码。(感谢 灵尘居提供 )

<?php $the_query = new WP_Query( 'posts_per_page=-1&ignore_sticky_posts=1' ); //update: 加上忽略置顶文章
					$year=0; $mon=0; $i=0; $j=0;
					$all = array();
					$output = '<div id="archives">';
					while ( $the_query->have_posts() ) : $the_query->the_post();
						$year_tmp = get_the_time('Y');
						 $mon_tmp = get_the_time('n');
						 //var_dump($year_tmp);
						 $y=$year; $m=$mon;
						 if ($mon != $mon_tmp && $mon > 0) $output .= '</div></div>';
						 if ($year != $year_tmp) {
							$year = $year_tmp;
							$all[$year] = array();
						 }

						 if ($mon != $mon_tmp) {
							$mon = $mon_tmp;
							array_push($all[$year], $mon);
							$output .= "<div class='archive-title' id='arti-$year-$mon'><h3>$year-$mon</h3><div class='archives archives-$mon' data-date='$year-$mon'>"; //输出月份
						 }
						 $output .= '<div style="font-size:14px" class="brick"><a href="'.get_permalink() .'"><span class="time">'.get_the_time('n-d').'</span> '.get_the_title() .'<em>('. get_comments_number('0', '1', '%') .')</em></a></div>'; //输出文章日期和标题
					endwhile;
					wp_reset_postdata();
					$output .= '</div></div></div>';
					echo $output;

					$html = "";
					$year_now = date("Y");
					foreach($all as $key => $value){
						$html .= "<li class='year' id='year-$key'><a href='#' class='year-toogle' id='yeto-$key'>$key</a><ul class='monthall'>";
						for($i=12; $i>0; $i--){
							if($key == $year_now && $i > $value[0]) continue;
							$html .= in_array($i, $value) ? ("<li class='month monthed' id='mont-$key-$i'>$i</li>") : ("<li class='month'>$i</li>");
						}
						$html .= "</ul></li>";
					}
				?>
			
			<?php
			wp_link_pages(
				array(
					'before' => '<div class="page-links">' . __( 'Pages:', 'twentytwelve' ),
					'after'  => '</div>',
				)
			);
?>

3.然后找到刚才修改的 archives.php 文件,中找到如下代码

<?php get_template_part( 'content', 'page' ); ?>

替换成

<?php get_template_part( 'content', 'archives' ); ?>

这句代码的意思就是如果存在 content-archives.php 文件,则调取 content-archives.php文件,如果没有 content-archives.php 文件,则调取 content.php 文件,默认代码是调取 content-page.php 默认输出模版。

4.创建页面,选择 archives 页面模版,发布,OK了。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注