Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
カスタム投稿タイプとタクソノミー、rewriteルール追加をまとめた関数
/*
* カスタム投稿タイプ(本)を追加します。
* タクソノミーとrewriteルールも追加します。
*
*/
add_action( 'init', 'create_post_type_book' );
function create_post_type_book() {
// rewriteルールをつくるために
global $wp_rewrite;
// カスタム投稿タイプの設定
$labels = array(
'name' => _x('本', 'post type general name'),
'singular_name' => _x('本', 'post type singular name'),
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'exclude_from_search' => false,
'query_var' => true,
'rewrite' => array('slug' => 'book/%book-cat%', 'with_front' => true, 'hierarchical' => true),
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => 4,
'supports' => array('title', 'editor', 'thumbnail', 'author', 'trackbacks', 'comments', 'revisions'),
);
register_post_type('post_type_book', $args);
//カスタムタクソノミーの設定
$labels = array(
'name' => _x( 'カテゴリー', 'taxonomy general name' ),
'singular_name' => _x( 'カテゴリー', 'taxonomy singular name' ),
'add_new_item' => __( '新規カテゴリーを追加' ),
'edit_item' => __( 'カテゴリーの編集' ),
'update_item' => __( 'カテゴリーを更新' ),
'search_items' => __( 'カテゴリーを検索' ),
);
$args = array(
'labels' => $labels,
'public' => true,
'show_ui' => true,
'show_admin_column' => true,
'rewrite' => array('slug' => 'post_type_book_category', 'with_front' => true),
'hierarchical' => true,
'update_count_callback' => '_update_post_term_count',
);
register_taxonomy('post_type_book_category', 'post_type_book', $args);
// %book-cat%を定義
$wp_rewrite->add_rewrite_tag( '%book-cat%', '[a-zA-Z0-9_]','post_type_book=');
// book/novel/samplebook/ でsamplebookのカスタム投稿記事ページが表示されるようrewriteツールを加える
add_rewrite_rule('^book/([^/]+)/([^/]+)/?$','index.php?post_type_book=$matches[2]','top');
// book/novel/ でnovel一覧ページが表示されるようrewriteツールを加える
add_rewrite_rule('^book/([^/]+)/?$','index.php?post_type_book_category=$matches[1]&post_type=post_type_book','top');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment