プラグインを使わずにカテゴリ別のアーカイブリストを出力する
Archives for a categoryが削除された為、
プラグインを使わずにカテゴリ別のアーカイブリストを出力するメモ。
function.phpにリスト出力時にカテゴリIDを付与する記述
<?php
add_filter('getarchives_where', 'custom_archives_where', 10, 2);
add_filter('getarchives_join', 'custom_archives_join', 10, 2);
function custom_archives_join($x, $r) {
global $wpdb;
$cat_ID = $r['cat'];
if (isset($cat_ID)) {
return $x . " INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)";
} else {
return $x;
}
}
function custom_archives_where($x, $r) {
global $wpdb;
$cat_ID = $r['cat'];
if (isset($cat_ID)) {
return $x . " AND $wpdb->term_taxonomy.taxonomy = 'category' AND $wpdb->term_taxonomy.term_id IN ($cat_ID)";
} else {
$x;
}
}
function wp_get_cat_archives($opts, $cat) {
$args = wp_parse_args($opts, array('echo' => '1')); // default echo is 1.
$echo = $args['echo'] != '0'; // remember the original echo flag.
$args['echo'] = 0;
$args['cat'] = $cat;
$archives = wp_get_archives(build_query($args));
$archs = explode('</li>', $archives);
$links = array();
foreach ($archs as $archive) {
$link .= strpos($archive, '?') === false ? '?' : '&';
$link .= 'cat=' . $cat;
array_push($links, $link);
}
$result = implode('</li>', $links);
if ($echo) {
echo $result;
} else {
return $result;
}
}
?>category.phpカテゴリテンプレートで月別アーカイブなら年月情報を追加
<?php
$cat = get_current_category();
$cat_name = get_cat_name($cat->cat_ID);
if( is_month() ){//月別アーカイブ一覧だったら
$m = get_query_var('m');
$year_num = substr($m,0,4);
$month_num = substr($m,4,2);
$cat_name .= '/'.$year_num.'年'.$month_num.'月';
$args = array(
'cat' => $cat->cat_ID,
'year' => $year_num,
'monthnum' => $month_num
);
}else{
$args = array(
'cat' => $cat->cat_ID,
);
}
?>
<h1><?php echo $cat_name;?></h1>
<?php $the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post();?>
ここに記事出力
<?php endwhile;endif; ?>参考:WordPress でカテゴリ別アーカイブ
RECENT POSTS
SEARCH





