WordPress 3.1 为自定义文章类型加入了一个新参数,我们终于可以用原生方法为自定义文章类型建立索引页(index)和归档页(archive)了。假设你的博客有一个文章类型为 work,那么你可以在主题里添加 archive-work.php 和 single-work.php 这两个文件分别作为 work 的归档页面和文章页面模板。
接下来,我们需要在注册 work 这个文章类型时添加 ‘has_archive’ => true 这个参数使 work 支持归档(其实这个就是 3.1 新加入的参数)。因此完整的注册文章类型的总参数就变为以下代码:
add_action('init', 'my_custom_init');
function my_custom_init() {
$labels = array(
'name' => _x('work', 'post type general name'),
'singular_name' => _x('work', 'post type singular name'),
'add_new' => _x('Add New', 'work'),
'add_new_item' => __('Add New work'),
'edit_item' => __('Edit work'),
'new_item' => __('New work'),
'view_item' => __('View work'),
'search_items' => __('Search work'),
'not_found' => __('No work found'),
'not_found_in_trash' => __('No work found in Trash'),
'parent_item_colon' => '',
'menu_name' => 'Work'
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => true,
'menu_icon' => get_stylesheet_directory_uri() . '/article16.png',
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'supports' => array('title','editor','author','thumbnail','excerpt','comments','custom-fields','revisions'),
'taxonomies' => array('post_tag','category')
);
register_post_type('work',$args);
}
最后我们需要清除重定向缓存,使 WordPress 能正确跳转到自定义文章类型的归档页:
add_action('admin_init', 'flush_rewrite_rules');
说了半天,怎么建立自定义文章类型的索引页呢?我们可以举一反三,为 archive-work.php 加上下面的模板头:
// Template Name: archive of works
via:http://codecto.com/2011/01/wordpress-3-1-custom-post-type-index-page/