add_action( 'init', 'codex_custom_init' );
function codex_custom_init() {
$labels = array(
'name' => _x('Books', 'post type general name'),
'singular_name' => _x('Book', 'post type singular name'),
'add_new' => _x('Add New', 'book'),
'add_new_item' => __('Add New Book'),
'edit_item' => __('Edit Book'),
'new_item' => __('New Book'),
'all_items' => __('All Books'),
'view_item' => __('View Book'),
'search_items' => __('Search Books'),
'not_found' => __('No books found'),
'not_found_in_trash' => __('No books found in Trash'),
'parent_item_colon' => '',
'menu_name' => 'Books'
);
$args = array(
'labels' => $labels,
'public' => true,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'query_var' => true,
'rewrite' => true,
'capability_type' => 'post',
'has_archive' => true,
'hierarchical' => false,
'menu_position' => null,
'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )
);
register_post_type('book',$args);
}
自定義文章類型的默認固定鏈接格式
Custom Post Type默認的固定鏈接格式是‘post-slug/postname’,如果沒有指定slug,則用post type作為slug,本例中沒有指定,所有post slug就是book。
與固定鏈接相關的參數有rewrite、和slug
rewrite參數指定是否開啟固定鏈接功能,rewrite默認是true,如果設置成false,假設我創建了壹個book類型的文章,標題是“Harry Potter Book”,產生的鏈接如下:
結尾是否有反斜杠,取決於設置-固定鏈接中的格式結尾是否有反斜杠,建議這裏結尾不要帶反斜杠,否則可能出現
指向同壹個地址的情況,對搜索引擎不友好。
如何修改自定義文章類型的固定鏈接格式
假設我們創建了book類型的文章,並且用中文當做文章標題,那麽默認產生的鏈接也將是中文,中文鏈接通常會編碼,比較長,分享不方便。妳可以手動輸入英文slug,也可以通過修改固定鏈接格式讓了鏈接更簡短。
要達到這個目的:
創建新的rewrite規則翻譯URL
添加filter(post_type_link),當get_the_permalink()函數調用時,返回正確的鏈接格式
下面有兩段代碼,都可以實現這個要求,代碼加到functions.php中,並且要到後臺-設置-固定鏈接中重新保存固定鏈接,代碼才能生效。
代碼段1
add_action('init', 'custom_book_rewrite');
function custom_book_rewrite() {
global $wp_rewrite;
$queryarg = 'post_type=book&p=';
$wp_rewrite->add_rewrite_tag('%qid%', '([^/]+)', $queryarg);
$wp_rewrite->add_permastruct('book', '/book/%qid%.html', false);
}
add_filter('post_type_link', 'custom_book_permalink', 1, 3);
function custom_book_permalink($post_link, $post = 0) {
global $wp_rewrite;
if ( $post->post_type == 'book' ){
$post = &get_post($id);
if ( is_wp_error( $post ) )
return $post;
$newlink = $wp_rewrite->get_extra_permastruct('book');
$newlink = str_replace("%qid%", $post->ID, $newlink);
$newlink = home_url(user_trailingslashit($newlink));
return $newlink;
} else {
return $post_link;
}
}