Web production note

 【更新日 :

【WordPress】投稿記事の年度一覧・年度と月一覧を表示させる

Category:
WordPress

投稿記事の年度一覧・年度と月一覧を表示させる最小限のサンプルコードです。
投稿・カスタム投稿のいずれにも対応しています。

年度一覧

<?php
	//記事の年度一覧
	$args = array(
		'post_type' => 'post',
		'posts_per_page' => -1,
		'post_status' => array(
			'publish'
		 )
	);
	$posts = get_posts( $args );
	$year_current = '';
	foreach( $posts as $key => $post_val ) {
		//記事の年度を取得
		$post_year = get_the_time('Y',$post_val->ID);
		if ($year_current != $post_year) {
			$year_current = $post_year;
			echo $year_current;
		}
	}
?>

年度+月一覧

月一覧も表示させる場合は、年度一覧の中に更にループを追加します。

<?php
	//記事の年度と月一覧
	$args = array(
		'post_type' => 'post',
		'posts_per_page' => -1,
		'post_status' => array(
			'publish'
		 )
	);
	$posts = get_posts( $args );
	$year_current = '';
	$month_current = '';
	foreach( $posts as $key => $post_val ) {
		//記事の年度を取得
		$post_year = get_the_time('Y',$post_val->ID);
		if ($year_current != $post_year) {
			$year_current = $post_year;
			echo $year_current;
			
			//記事の月を取得
			foreach( $posts as $key => $post_val_month ) {
				$post_month = get_the_time('n',$post_val_month->ID);
				if ($year_current == get_the_time('Y',$post_val_month->ID)) {
					if ($month_current != $post_month) {
						$month_current = $post_month;
						echo $month_current;
					}
				}
			}
			
		}
	}
?>