WordPress 修改自定義文章類型的固定鏈接結構

關於自定義文章類型和固定鏈接結構,大家可以想回顧一下:

自定義文章類型默認輸入的固定鏈接結構爲 /%postname%  。假設我們添加的自定義文章類型爲 book ,那麼默認輸出的 book 文章鏈接一般爲 http://域名/book/slug (slug爲標題別名)。如果文章標題是中文(比如:一本好書),而且你沒有手動或者使用插件翻譯爲非中文的 slug (a-nice-book),那麼顯示的鏈接就會是http://域名/book/一本好書 ,這樣一來,文章鏈接的中文部分就會顯示成亂碼,實在不符合我們的審美標準了。

那麼,我們可以將 /%postname% 改爲 /%post_id% 或 /%post_id%.html 樣式,使用ID來顯示。要實現這個目的,可以使用文章開頭提到的 Custom Post Type Permalinks 插件。如果你是插件或主題開發者,一般都喜歡直接通過代碼定義好默認的固定鏈接結構。

可以在插件函數文件或主題的functions.php 文件添加下面的代碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
 * 設置 book 這種自定義文章類型的固定鏈接結構爲 ID.html 
 * http://www.wpdaxue.com/custom-post-type-permalink-code.html
 */
add_filter('post_type_link', 'custom_book_link', 1, 3);
function custom_book_link( $link, $post = 0 ){
	if ( $post->post_type == 'book' ){
		return home_url( 'book/' . $post->ID .'.html' );
	} else {
		return $link;
	}
}
add_action( 'init', 'custom_book_rewrites_init' );
function custom_book_rewrites_init(){
	add_rewrite_rule(
		'book/([0-9]+)?.html$',
		'index.php?post_type=book&p=$matches[1]',
		'top' );
}

以上代碼就可以輸出形如 /book/123.html 的鏈接。請將代碼中所有 book 替換爲你的自定義文章類型。

如果你要同時定義多種自定義文章類型,可以使用下面的代碼:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
 * 設置多種自定義文章類型的固定鏈接結構爲 ID.html
 * http://www.wpdaxue.com/custom-post-type-permalink-code.html
 */
$mytypes = array(//根據需要添加你的自定義文章類型
	'type1' => 'slug1',
	'type2' => 'slug2',
	'type3' => 'slug3'
	);
add_filter('post_type_link', 'my_custom_post_type_link', 1, 3);
function my_custom_post_type_link( $link, $post = 0 ){
	global $mytypes;
	if ( in_array( $post->post_type,array_keys($mytypes) ) ){
		return home_url( $mytypes[$post->post_type].'/' . $post->ID .'.html' );
	} else {
		return $link;
	}
}
add_action( 'init', 'my_custom_post_type_rewrites_init' );
function my_custom_post_type_rewrites_init(){
	global $mytypes;
	foreach( $mytypes as $k => $v ) {
		add_rewrite_rule(
			$v.'/([0-9]+)?.html$',
			'index.php?post_type='.$k.'&p=$matches[1]',
			'top' );
	}
}

參考資料:http://www.solagirl.net/custom-post-type-permalink.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章