LoginSignup
0
0

More than 5 years have passed since last update.

WordPress投稿カテゴリーリスト、年別アーカイブリストを表示する

Posted at

内容

WordPress投稿のカテゴリ、年別アーカイブのリスト表示のコードです。
毎回、ググっているのでメモしておきます。

解決コード

カテゴリリスト

archive.php

<ul class="p-archives__list">
<?php
$args = array(
'orderby' => 'name'
);
$categories = get_categories( $args );
foreach ( $categories as $category ) {
echo '<li class="p-archives__item"><a href="/news/'. $category->slug . '">' . $category->name . '</a></li>';
}
?>
</ul>

年アーカイブリスト

archive.php

<?php // 年別アーカイブリストを表示
$year=NULL; // 年の初期化
$args = array( // クエリの作成
'orderby' => 'date', // 日付順で表示
'order'   => 'DESC',
'posts_per_page' => -1 // すべての投稿を表示
);
$the_query = new WP_Query($args); if($the_query->have_posts()){ // 投稿があれば表示
echo '<ul class="p-archives__list">';
while ($the_query->have_posts()): $the_query->the_post(); // ループの開始
if ($year != get_the_date('Y')){ // 同じ年でなければ表示
$year = get_the_date('Y'); // 年の取得
echo '<li class="p-archives__item"><a href="'.home_url( '/', 'http' ).'news/'.$year.'">'.$year.'年</a></li>'; // 年別アーカイブリストの表示
}
endwhile; // ループの終了
echo '</ul>';
wp_reset_postdata(); // クエリのリセット
}
?>

参考サイト

【WordPress】自由なHTMLでカテゴリーリストを作りたいときの方法 | 福岡のホームページ制作・SEO対策ならアイドットデザイン
https://idotdesign.net/blog/web/wordpress/howtomake-categorylist/

WordPress 年別アーカイブリストを表示する方法 - by Takumi Hirashima
https://hirashimatakumi.com/blog/3962.html

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