カスタム投稿タイプで、該当する投稿タイプのアーカイブリスト表示をさせる方法1

wp_list_archives()関数は、デフォルトではカスタム投稿タイプに対応していない。

そこで、各カスタム投稿タイプのページで、そのカスタム投稿タイプのアーカイブリストを表示することができるようにしてみた。

functions.php

functions.phpに以下のコードを書き加える。

/*
1.wp_list_archives()関数をカスタマイズ
*/

//1-1.wp_list_archives()で使うSQL文のうち、WHERE句をカスタマイズする関数
function customPost_getarchives_where( $where, $r ) {
    $myPostType = get_post_type();
    $where = str_replace( '\'post\'', '\'' . $myPostType . '\'' , $where );
    return $where;
}

//1-2.wp_list_archives()でaタグを出力をカスタマイズする関数
function customPost_get_archives_link($linkHtml) {
    $repBlogUrl = str_replace(array(':', '/', '.'), array('\:', '\/', '\.'), get_bloginfo('url'));
    $addLink = get_post_type();
    $linkHtml = preg_replace("/href='(" . $repBlogUrl . ")\/([0-9]{4}\/[0-9]{1,2}\/)'/", "href='$1/" . $addLink. "/$2'", $linkHtml);
    return $linkHtml;
}



/*
2.http://サイトのURL/カスタム投稿タイプ/年/月/ のurlを受け取った時に、該当するカスタム投稿タイプのarchiveとして認識するように、リライトルールを設定する。
*/

function extra_add_rewrite_rules( $wpRewrite ) {
    $postTypes = custom_post_types_array();
    $newRules = array();
 
    foreach($postTypes as $key):
        $newRules += array(
            //以下、アーカイブを設定
             '(' . $key . ')/([0-9]{4})/([0-9]{1,2})'
            => 'index.php?post_type=' . $key . '&year=' . $wpRewrite->preg_index(2) . 'monthnum=' . $wpRewrite->preg_index(3),
            '(' . $key . ')/([0-9]{4})'
            => 'index.php?post_type=' . $key . '&year=' . $wpRewrite->preg_index(2),
        );
    endforeach;
    $wpRewrite->rules = $newRules + $wpRewrite->rules;
}

add_action('generate_rewrite_rules', 'extra_add_rewrite_rules');



/*
3.現在使用しているカスタム投稿タイプの一覧を取得し、インデックス配列の形式に置換
他でも利用したので、わざわざ作っていますが、今回の目的だけでしたら、get_post_types()関数をそのまま2.で利用しても構いません。

get_post_types()関数の参考サイト
(1)関数リファレンス/get post types - WordPress Codex 日本語版 http://wpdocs.sourceforge.jp/%E9%96%A2%E6%95%B0%E3%83%AA%E3%83%95%E3%82%A1%E3%83%AC%E3%83%B3%E3%82%B9/get_post_types
(2)get_post_types:WordPress私的マニュアル http://elearn.jp/wpman/function/get_post_types.html
*/

function custom_post_types_array($public = true){
    $args = array(
        'public'   => $public,
        '_builtin' => false
    );
    $postTypes = get_post_types($args);
    $postTypesArray = array();
	
    foreach($postTypes as $key):
        array_push($postTypesArray, $key);
    endforeach;
	
    return $postTypesArray;
}

使い方

wp_list_archives()関数の前後を、以下のように挟みます。

add_filter( 'getarchives_where', 'customPost_getarchives_where', 10, 2 );
add_filter( 'get_archives_link', 'customPost_get_archives_link' );
wp_list_archives();
remove_filter( 'getarchives_where', 'customPost_getarchives_where', 10, 2 );
remove_filter( 'get_archives_link', 'customPost_get_archives_link' );

注意点としては、リライトルールを書き換えているので、新しい投稿タイプを追加したら、一度だけ、「管理画面>パーマリンク設定」を開いて、何もしないま「保存」を押してください。

※新しい投稿タイプを追加した際に、パーマリンク設定を更新するのは必須作業なので、このカスタマイズに限ったことではありませんが。