年別・月別の件数つきアーカイブを取得する方法

6817 Views
WordPress
年別・月別の件数つきアーカイブを取得する方法

デフォルトの投稿、自分で追加したカスタム投稿のアーカイブを件数を含めて取得する関数は準備されていないと思います。
※あったらすみません。。。

なので投稿の種類を問わず件数つきのアーカイブを取得する関数を作ったので紹介します。

SNSでシェア♪

スポンサーリンク

目次

以下の関数をfunctions.phpに追加する

//デフォルト・カスタム投稿のアーカイブを取得
function customPostArchives($postType='post', $_type='year') {
	global $wpdb;

	$postTypes   = is_array($postType) ? $postType : array($postType);
	$lastChanged = wp_cache_get('last_changed', 'posts');
	if (!$lastChanged) {
		$lastChanged = microtime();
		wp_cache_set('last_changed', $lastChanged, 'posts');
	}

	$postTypeConds = array();
	foreach ($postTypes as $type) {
		$postTypeConds[] = $wpdb->prepare("post_type = %s", $type);
	}
	$postTypeCondition = '('.implode(' OR ', $postTypeConds).')';
	
	if ($_type == 'month') {
		$query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts FROM {$wpdb->posts} WHERE {$postTypeCondition} AND post_status = 'publish' GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date DESC";
	} else {
		$query = "SELECT YEAR(post_date) AS `year`, count(ID) as posts FROM {$wpdb->posts} WHERE {$postTypeCondition} AND post_status = 'publish' GROUP BY YEAR(post_date), YEAR(post_date) ORDER BY post_date DESC";
	}

	$key     = md5($query);
	$key     = "customPostArchives:{$key}:{$lastChanged}";
	$results = $wpdb->get_results($query);
	if (!$results = wp_cache_get($key, 'posts')) {
		$results = $wpdb->get_results($query);
		wp_cache_set($key, $results, 'posts');
	}

	return $results;
}

使い方として、
・第一引数にポストタイプを入れる【デフィルト:post】
・第二引数に「month」or「year」(月別 or 年別)を指定する【デフォルト:年別】

年別の使用例

$postYearArchives = customPostArchives('post', 'year');	//「投稿」の「年別」アーカイブを取得
foreach ($postYearArchives as $v) {
	$year  = $v->year;	//年を取得
	$count = $v->posts;	//投稿の数を取得

	echo "<li><a href=\"/{$year}/\">{$year}年({$count}件)</a></li>";
}

月別の使用例

$postMonthArchives = customPostArchives('post', 'month');	//「投稿」の「月別」アーカイブを取得
foreach ($postMonthArchives as $v) {
	$year  = $v->year;	//年を取得
	$month = $v->month;	//月を取得
	$count = $v->posts;	//投稿の数を取得

	echo "<li><a href=\"/{$year}/{$month}/\">{$year}年{$month}月({$count}件)</a></li>";
}

取得したい投稿のタイプに合わせて「post」の部分を変更してください。
以上。

SNSでシェア♪

スポンサーリンク

関連記事