WordPressでカテゴリー別のアーカイブを、サイドバーに表示しようとすると、デフォルトには該当する機能がありません。
意外と面倒。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function year_and_category_archive() { | |
global $wp_rewrite; | |
$wp_rewrite->add_permastruct( 'date', '/%year%/%category%/', false ); | |
} | |
add_action('init', 'year_and_category_archive'); | |
//年別xカテゴリー別アーカイブの生成 | |
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; | |
$tag = ($args['format'] === 'option') ? 'option' : 'li'; | |
$archives = wp_get_archives(build_query($args)); | |
$archs = explode('</'.$tag.'>', $archives); | |
$links = array(); | |
$cat = get_the_category(); | |
$cat_slug = $cat[0]->category_nicename; // カテゴリースラッグ | |
$cat = $cat_slug ; | |
foreach ($archs as $archive) { | |
$link =preg_replace("/='([^']+)'/", "='$1/{$cat}/'", $archive); | |
array_push($links, $link); | |
} | |
$result = implode('</'.$tag.'>', $links); | |
if ($echo) { | |
echo $result; | |
} else { | |
return $result; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php wp_get_cat_archives('type=yearly', 9); ?> |
パーマリンクの構造でうまく動かいこともあります。
/%category%//%post_id%/
でうまくいかないことがあって、%post_id%を%postname%にして試してみたら、うまくいったことがありました。
パーマリンク設定は、上記のfunctionsを書き換えた後、保存し直さないと動いてくれませんでした。
サブカテゴリーがある場合、サブカテまで判別されるとちょっとややこしいので、
サブカテ表示の状態でも親カテのアーカイブに表示にしたい場合、少しだけ変更します。