固定ページに指定カテゴリの一覧を表示し、ページネーションをつける

最終更新日

固定ページに記事一覧を表示させたいことがよくあるので、カテゴリと表示件数を指定し件数を超えた場合はページネーションでページ送りできるコードをつくってみました。

固定ページのテンプレート

<?php
if ( is_page( '固定ページのスラッグ' ) ) {
	$args = array(
		'posts_per_page' => 5, //表示件数
		'cat' => 1, //カテゴリID
		'paged' => $paged,
		'orderby' => 'post_date',
		'order' => 'DESC',
		'post_type' => 'post',
		'post_status' => 'publish'
	);
}

$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ): while ( $the_query->have_posts() ): $the_query->the_post();

//カテゴリ情報を取得
$cat = get_the_category();
$cat_id = $cat[ 0 ]->cat_ID;
?>

<div class="<?php foreach($cat as $c) {echo ' '.$c->category_nicename;} ?>">
<p><span class="post-date"><?php the_time('Y.m.d'); ?></span>
<?php
	foreach ( $cat as $c ) { //カテゴリ名を表示	
		echo '<span class="label label-warning ' . $c->category_nicename . '"><a href="' . $c->category_nicename . '	">' . $c->cat_name . '</a></span> ';
	}
?>
</p>
	<h3><a href="<?php the_permalink() ?>"><?php the_title() ?></a></h3>
	<p><?php the_content() ?></p>
	<?php	edit_post_link();	//ログイン時に編集リンクを表示 ?>
</div>
<?php endwhile; ?>

<?php else: ?>
<p>お探しの記事、ページは見つかりませんでした。</p>
<?php endif; ?>

<div class="pagenation">
<?php
	//ページネーション
	if ( $the_query->max_num_pages > 1 ) {
		echo paginate_links( array(
		'base' => get_pagenum_link( 1 ) . '%_%',
		'format' => 'page/%#%/',
		'current' => max( 1, $paged ),
		'total' => $the_query->max_num_pages,
		'type' => 'list',
		'prev_text' => '« 前へ',
		'next_text' => '次へ »'
		) );
	}
	wp_reset_postdata();
?>
</div>

CSS

CSSを以下のようにするとBootstrapのページネーションっぽくなります。

.page-numbers {
	display: inline-block;
	padding-left: 0;
	margin: 20px 0;
}
.page-numbers > li { display: inline; }
.page-numbers > li > a, .page-numbers > li > span {
	position: relative;
	float: left;
	padding: 6px 12px;
	line-height: 1.42857143;
	text-decoration: none;
	color: #337ab7;
	background-color: #ffffff;
	border: 1px solid #dddddd;
	margin-left: -1px;
	color: #509256;
}
.page-numbers > li:first-child a, .page-numbers > li:first-child span {
	margin-left: 0;
	border-bottom-left-radius: 4px;
	border-top-left-radius: 4px;
}
.page-numbers > li:last-child a, .page-numbers > li:last-child span {
	border-bottom-right-radius: 4px;
	border-top-right-radius: 4px;
}
.page-numbers > li > a:hover, .page-numbers > li > span:hover, .page-numbers > li > a:focus, .page-numbers > li > span:focus {
	z-index: 2;
	color: #3B6E39;
	background-color: #eeeeee;
	border-color: #dddddd;
}
.page-numbers .current {
	z-index: 3;
	color: #ffffff;
	background-color: #509256;
	border-color: #3B6E39;
	cursor: default;
}
.page-numbers > .disabled > span, .page-numbers > .disabled > span:hover, .page-numbers > .disabled > span:focus, .page-numbers > .disabled > a, .page-numbers > .disabled > a:hover, .page-numbers > .disabled > a:focus {
	color: #777777;
	background-color: #ffffff;
	border-color: #dddddd;
	cursor: not-allowed;
}