wordpressでは偶に痒いところがあり、その一つに月別アーカイブの取得があります。
wp_get_archives()
で取得はできるものの、htmlで取得されるため思うように出力に使えないことがあります。
なので今回はそれをもとにWordpressの月別アーカイブを配列で年別に取得する関数を作りました。
下記をfunctionsに追記
function get_monthly_archive_array($post_type = ''){
$archive = array(
'type' => 'monthly',
'limit' => '',
'format' => 'html',
'before' => '',
'after' => '',
'show_post_count' => true,
'echo' => false,
'order' => 'ASC',
'post_type' => $post_type
);
// HTML形式で取得
$base_html = wp_get_archives($archive);
// liをごとに分割
$item_list = preg_split("/(?<=(li>))\\n(?=(<li))/m",$base_html);
$archive_list = [];
$pattern = '/<a\\s+href="([^"]+)"[^>]*>([^<]+)\\((.*?)\\)<\\/a>/';
foreach ( $item_list as $item ){
// クォートを統一
$item = str_replace("'",'"',$item);
// 取り出したい値を正規表現で取り出し配列に格納
if (preg_match($pattern, $item, $matches)) {
$href = $matches[1];
$text = $matches[2];
$count = $matches[3];
preg_match('/(\\d{4})年(\\d{1,2})月/', $text, $text_matches);
$archive_list[$text_matches[1]][] = [
'month' => $text_matches[2],
'link' => $href,
'count' => $count
];
}
}
// 配列を返す
return array_reverse($archive_list,true);
}
各所の解説はコード上にコメントアウトで入れています。
配列は下記のような形で出力されます。
(見やすいようにJSONで出力)
{
"2023": [
{
"month": "1",
"link": "<http://localhost:0000/news/2023/01/>",
"count": "1"
},
{
"month": "3",
"link": "<http://localhost:0000/news/2023/03/>",
"count": "2"
},
{
"month": "4",
"link": "<http://localhost:0000/news/2023/04/>",
"count": "3"
}
],
"2022": [
{
"month": "1",
"link": "<http://localhost:0000/news/2022/01/>",
"count": "1"
}
]
}
後はこれを自分の使いたいように整形するだけです。
出力例(出力したい場所に記述)
detailsタグで出力する場合
<?php
// 今回はデフォルトの「投稿」を取得してみますがカスタム投稿でも取得可能です。
$archive_arr = get_monthly_archive_array('post');
$archive_html = '';
// 配列をforeachで回してHTMLを記述
foreach ( $archive_arr as $year => $items ){
$archive_html .= '<details>';
$archive_html .= ' <summary>'.$year.'年</summary>';
$archive_html .= ' <ul>';
foreach ($items as $item) {
$archive_html .= ' <li><a href="'.$item['link'].'">'.$item['month'].'月</a></li>';
}
$archive_html .= ' </ul>';
$archive_html .= '</details>';
}
// HTMLを出力
echo $archive_html;
?>
ul liタグで出力する場合
<ul>
<?php
$archive_arr = get_monthly_archive_array($postTypeSlug);
$archive_lis = '';
foreach ( $archive_arr as $year => $items ){
$archive_lis .= '<li>';
$archive_lis .= ' <b data-open-acd="archive-acd-'.$year.'">'.$year.'年</b>';
$archive_lis .= ' <ul>';
foreach ($items as $item) {
$archive_lis .= ' <li><a href="'.$item['link'].'">'.$item['month'].'月</a></li>';
}
$archive_lis .= ' </ul>';
$archive_lis .= '</li>';
}
echo $archive_lis;
?>
</ul>
偶に痒いところに手が届かないWordPressですが、その不便なところを解消する方法として、ぜひお試しください。
■□■□■□■□■□■□■□■□■□■□
営業時間:平日9:00〜18:00
●福岡オフィス
〒810-0042
福岡市中央区赤坂1-12-6 赤坂Sビル2F
TEL:092-726-5550 FAX:092-726-5558
●宮崎出張所
〒880-0001
宮崎県宮崎市橘通西3-10-32
宮崎ナナイロ東館8FATOMica内
⇒ メールでのお問合せ
⇒ ホームページ制作実績
⇒ 会社案内
■□■□■□■□■□■□■□■□■□■□