技術ブログ
月別アーカイブへのリンクを表示する方法
月別アーカイブへのリンクを表示する方法
月別アーカイブへのリンクを表示する方法
wp_get_archives( $args )で$argsに条件を入れておけば表示されます。年でまとめてアコーディオンにする方法を説明します。。
概要
月別アーカイブへのリンクを、年でまとめてアコーディオンにするためには自分で関数を書く必要があります。
WordPressで用意された関数
'monthly', //表示するアーカイブリストの種類 年別の場合はyearly 'limit' => '', //取得するアーカイブ数 12ヶ月分なら12 'format' => 'html', 'before' => '', 'after' => '', 'show_post_count' => 0, //投稿数を表示するかどうか 'echo' => 1, 'order' => 'DESC', 'post_type' => 'blog' //カスタム投稿タイプ slug名'blog' の場合 ); wp_get_archives( $args ); ?>
この場合表示はされますが、2021年01月 2021年02月…という具合に並列的に表示されるだけで、階層化されていません。
階層化されていないために、アコーディオンに対応することが出来ません。
自作関数
get_results("SELECT DISTINCT MONTH( post_date ) AS month ,
YEAR( post_date ) AS year,
COUNT( id ) as post_count FROM $wpdb->posts
WHERE post_status = 'publish' and post_date <= now( )
and post_type = '{$target_post_type}'
GROUP BY month , year
ORDER BY year,month DESC");
foreach($months as $month) :
$year_loop = $month->year;
//年月情報の年が前回のループ時と同一年かどうかを判定
//同一年でない場合には年の終了タグを入れる
if ($year_loop != $year_prev_loop){
//初回ループ時のみは終了タグを入れない
if ($year_prev_loop != null){
$temp_body.='';
}
//月別アーカイブ、あるいはシングルの場合は現在の年がループ中の年と一致する場合はアコーディオンを自動で開くためにclassを入れる
$temp_class="";
if( is_month() || is_single() ){
if( $mycurrent_year===$month->year ){
$temp_class = ' class="minus"';
}
}
$temp_body .= '- ';
}
//月別アーカイブ、あるいはシングルの場合は現在の年がループ中の年と一致する場合はアコーディオンを自動で開くためにclassを入れる
$temp_class="";
if( is_month() || is_single() ){
if( $mycurrent_year===$month->year && $mycurrent_month===$month->month ){
$temp_class =' class="current"';
}
}
$temp_body .='
- '; //デフォルト投稿タイプpostか否かでリンクの表示方法が異なるため分岐 //カスタム投稿タイプの場合は、あくまでpressx.jpテンプレートのルールに則っているので、適宜リンク表示は変えてください。 //pressx.jpテンプレートでは [ カスタム投稿タイプスラッグ ] / [年] / [月] がカスタム投稿タイプの場合の月別アーカイブのパーマリンクストラクトになります。 if ( $jnm_info['post-type']['slug']=='post' ){ $temp_body .='month, 1, $month->year)) . '">'; } else { $temp_body .='month, 1, $month->year)) . '">'; } $temp_body .= date("n", mktime(0, 0, 0, $month->month, 1, $month->year)) . '月'; $temp_body .=' '; $year_prev_loop = $year_loop; endforeach; $temp_body .='
-
{$temp_body}