WP 年月のアーカイブをカテゴリで絞る方法

sidebar.phpに下記を記載する

<?php
/*====================================================

月別アーカイブ

=====================================================*/
$cat_slug = 'album';←変える
$args = array(
  'category_name' => $cat_slug,
  'posts_per_page' => -1
);
$archive_query = new WP_Query($args);
while ($archive_query->have_posts()) {
  $archive_query->the_post();
  //年月毎に記事情報を配列に格納
  $archive_list[get_the_time('Y/n', $post->ID)][] = $post->post_title;
}
wp_reset_postdata();
?>
<?php
if ($archive_list) : ?>
  <ul>
    <?php foreach ($archive_list as $year_month => $archive) :
      $year_month_arr = explode('/', $year_month);
    ?>
      <li>
        <a href="<?php echo esc_url(home_url($year_month . '/?cat_slug=' . $cat_slug)) ?>">
          <?php echo $year_month_arr[0] . '年' . $year_month_arr[1] . '月' ?> </a>
      </li>
    <?php endforeach; ?>
  </ul>

<?php endif; ?>

date.phpを作成

<?php
//$category_nameがなければ引き渡した情報を格納します。(例:album)
if (!$category_name) {
  $category_name = $_GET['cat_slug'];
}

if (have_posts()) : ?>

  <ul class="archive-info-list flex">

    <?php while (have_posts()) : the_post();
      // 記事毎のカテゴリ取得
      $categories = get_the_category();
      $cat_id = $categories[0]->term_id;

      // アーカイブのカテゴリがアルバムだったらアルバムのみ表示する
      if ($category_name === "album") : ?>

        <?php if ($cat_id === 39) : ?>
          <li>
            <!-- 画像・リンク -->
            <?php if (has_post_thumbnail()) : ?>
              <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('medium'); ?></a>
            <?php endif; ?>
            <!-- 日付 -->
            <time itemprop=”datepublished”><?php echo get_the_date("Y/m/d"); ?></time>
            <!-- カテゴリ -->
            <?php
            if ($categories) {
              echo '<ul class="archive-info-cat">';
              foreach ($categories as $category) {
                echo '<li><a href="' . esc_url(get_category_link($category->term_id)) . '">' . $category->name . '</a></li>';
              }
              echo '</ul>';
            }
            ?>
            <!-- タイトル・リンク -->
            <h2 class="archive-info-title mb0"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
          </li>
        <?php endif; ?>

      <?php else :
        // アーカイブのカテゴリがアルバム以外ならアルバム以外を全て取得
      ?>
        <?php if ($cat_id !== 39) : ?>
          <p>アーカイブのカテゴリがアルバム以外ならアルバム以外を全て取得</p>
        <?php endif; ?>

    <?php endif;
    endwhile; ?>

  </ul>

<?php else : ?>

  <h2 class="no-post">記事が見つかりませんでした。</h2>

<?php endif; ?>

<?php
if (function_exists('pagination')) :
  pagination($wp_query->max_num_pages, get_query_var('paged'));
endif; ?>

<?php wp_reset_postdata(); ?>

【WordPress】wp_get_archivesを使わずに特定カテゴリーの年月アーカイブリストを表示したい|ホームページ制作は広島のリコネクト|ウェブサイトの制作から更新サポート・ブランディング・ウェブシステム開発まで