解決したと思ったのですが、他のカテゴリーのトップページの一覧まで絞り込んでしまって、他のカテゴリーのアーカイブ一覧が表示されなくなってしまいました。
なので、AIと検討しながら作った下記のコードが完成形になります。
(文字化け防止コードの指定もあり)
●はカテゴリーIDの番号、blogはこの場合のカテゴリースラッグです。
ドロップダウンで月別アーカイブの投稿数()も取得する
‘limit’ => 24, // 2年間分の月別アーカイブを取得
‘limit’ => ”, // 空にすると、全期間のアーカイブが表示される
sidebar.php
<div class="archive">
<h3>月別アーカイブ</h3>
<select name="archive-dropdown" onchange="document.location.href=this.options[this.selectedIndex].value;">
<option disabled selected value>選択してください</option>
<?php
$archives = wp_get_archives(array(
'type' => 'monthly',
'limit' => 12,
'echo' => false,
'format' => 'custom'
));
$dom = new DOMDocument();
@$dom->loadHTML(mb_convert_encoding($archives, 'HTML-ENTITIES', 'UTF-8')); // UTF-8に変換して解析
foreach ($dom->getElementsByTagName('a') as $link) {
$url = $link->getAttribute('href');
$filtered_url = add_query_arg('cat', ●, $url);
// 年・月を取得
preg_match('/(\d{4})\/(\d{2})/', $url, $matches);
if (!empty($matches)) {
$year = intval($matches[1]);
$month = intval($matches[2]);
// blogカテゴリーの投稿数を取得
$args = array(
'category__in' => array(●),
'year' => $year,
'monthnum' => $month,
'posts_per_page' => -1,
);
$posts = get_posts($args);
$post_count = count($posts);
} else {
$post_count = 0; // デフォルトで0を設定
}
echo '<option value="' . esc_url($filtered_url) . '">' . htmlspecialchars($link->nodeValue, ENT_QUOTES, 'UTF-8') . ' (' . $post_count . ')</option>';
}
?>
</select>
</div><!-- /archive -->
↓投稿数なしの場合
<div class="archive">
<h3>月別アーカイブ</h3>
<select name="archive-dropdown" onchange="document.location.href=this.options[this.selectedIndex].value;">
<option disabled selected value>選択してください</option>
<?php
$archives = wp_get_archives(array(
'type' => 'monthly',
'limit' => 12,
'echo' => false,
'format' => 'custom'
));
$dom = new DOMDocument();
@$dom->loadHTML(mb_convert_encoding($archives, 'HTML-ENTITIES', 'UTF-8')); // UTF-8に変換して解析
foreach ($dom->getElementsByTagName('a') as $link) {
$url = $link->getAttribute('href');
$filtered_url = add_query_arg('cat', ●, $url);
echo '<option value="' . esc_url($filtered_url) . '">' . htmlspecialchars($link->nodeValue, ENT_QUOTES, 'UTF-8') . '</option>';
}
?>
</select>
</div><!-- /archive -->
function.php の記述 他のカテゴリーのアーカイブに影響をあたえない設定
//特定カテゴリー月別アーカイブ(blogカテゴリーのスラッグblogのみ表示)
function filter_blog_archives($query) {
if ($query->is_main_query() && !is_admin() && is_archive()) {
// 特定のカテゴリースラッグ(blog)の場合のみ絞り込み
if (is_category('blog')) {
$query->set('category__in', array(●));
}
}
}
add_action('pre_get_posts', 'filter_blog_archives');