特定カテゴリーの年別投稿一覧(今度こそ解決!)
2022年1月13日
年別投稿一覧を年毎に括って表示したかったのだが、これがなかなかうまく行かず、紆余曲折を経てたどり着いた結果が以下。
つべこべ言わずに本当の正解を最初に掲載しておく。
作家さんサイトのartページの年別サムネイル一覧(アコーディオン)。
<section class="arts">
<?php
function archiveFunc($year)
{
$args = array(
'category_name' => 'artwork',
'posts_per_page' => -1,
'year' => $year
);
$post_query = new WP_Query($args);
if ($post_query -> have_posts()):
?>
<div class="works-box">
<div class="works-box-header">
<?php echo $year; ?>
<div class="arrows">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"><path d="M12 16a1 1 0 0 1-.64-.23l-6-5a1 1 0 1 1 1.28-1.54L12 13.71l5.36-4.32a1 1 0 0 1 1.41.15 1 1 0 0 1-.14 1.46l-6 4.83A1 1 0 0 1 12 16z"/></svg>
</div>
</div>
<div class="accordion_inner">
<div class="panel">
<?php while($post_query -> have_posts()) : $post_query -> the_post(); ?>
<div class="panel-inner">
<a href="<?php the_permalink(); ?>">
<div class="art-item">
<?php if( has_post_thumbnail() ): ?>
<?php echo get_the_post_thumbnail(); ?>
<?php else: ?>
<img src="<?php echo catch_that_image(); ?>" />
<?php endif; ?>
<div class="mask">
<div class="caption">
<?php the_title();?></div>
</div>
</div>
</a>
</div>
<?php endwhile; ?>
</div>
</div>
</div>
<?php endif;
wp_reset_query();
}
$thisyear = date('Y'); // 現在の西暦年を取得
for ($year=$thisyear; $year >= 2019; $year--) {
// $year >= で指定した年から現在の年までの記事を出力
archiveFunc($year); //関数の読み込み
}
?>
</section>
ほぼ完了していたのだが、記事の読み込みとループ箇所を間違えていた。
if ($post_query -> have_posts()):
の箇所と
while($post_query -> have_posts()) : $post_query -> the_post();
の箇所、あとはループを終了させる箇所と全て終わらせる箇所。
そもそもarchiveFunkという関数をfor文で2019年以降分繰り返しているので、1年分をしっかり出力することに注力すれば良かったのだ!