0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

WPのアーカイブページ(カテゴリー・タグなど)を固定ページで表示させる(複数タクソノミー&ページネーション対応)

Posted at

ワードプレスでカテゴリー・タグページなどのアーカイブページを固定ページ化したい」と考えることは一度はあると思いますが、任意の限定されたカテゴリーだけでなく、複数のタクソノミーに対応した方法です。

前提:カテゴリー・タグ名と固定ページのスラッグは連動させる

仮にカテゴリーのスラッグが fruit vegetable fish meat だとすれば、これらのカテゴリー一覧を表示させる固定ページのスラッグもそれぞれ、fruit vegetable fish meat とします。

まず、このルールを守らないと今回のコードは機能しません。

アーカイブページの内容を表示させる php ファイルに書くコード

<?php // 現在のページスラッグを取得(カテゴリー・タグ名と同名)
    global $post;
    $slug = $post->post_name;
?>

<?php
	$args = array(
		'paged' => $paged,
	    'post_type' => 'post',
	    'category_name' => $slug, // カテゴリーの場合
	    'tag' => $slug, // タグの場合
	    'posts_per_page' => 10,
	    'orderby' => 'date',
	    'order' => 'DESC',
	);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ): while ( $the_query->have_posts() ): $the_query->the_post(); ?>

<div class="loop">
	<h2><?php the_title(); ?></h2>
	<?php the_content() ?>
</div><!-- loop -->

<?php endwhile; 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,
    	'mid_size' => 2,
    	'current' => ($paged ? $paged : 1),
    	'prev_text' => '前',
    	'next_text' => '次',
		) );
	}
	wp_reset_postdata();
?>
</div><!-- pagenation -->

解説

解説というほどでもありませんが、最初に(当該の固定ページが表示された際に)当該ページのスラッグを取得し、WP_Query の配列に格納してループを回すといった形です。

配列の中身を変えてあげれば、カスタム投稿に対応したり、カスタムフィールドの値でループを回すなんてアイデアも広がるかと思います。

一意のカテゴリーだけ固定ページ化するなら必要ありませんが、複数のカテゴリー・タグをそれぞれの固定ページに表示したいといった場合には、上記のコードだけで対応できるので楽です。

繰り返しですが、タクソノミーのスラッグ固定ページのスラッグを連動させなければ動きません。

ワードプレスなんもわからんけど楽しい!

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?