本文的主題是wordpress主題開發:創建自定義文章類型post-type(3)——如何設置固定鏈接。在前面的文章中,我們注冊過一個wordpress自定義文章類型——商城,也在後台實現的“商城”模塊菜單的展示,在前台的文章也能正常展示。但是,前台的文章地址欄的地址不好看,因爲我們的文章标題基本都是中文的,所以代碼翻譯後會很長,有點難看,如下圖:
這樣的地址,看上去非常不美觀,也不利于網站的SEO。因爲,register_post_type()默認展示地址鏈接樣式是‘post-slug/postname’,也就是自定義文章類型名+文章名,而我們的文章名是中文,所以就造成了這種難看的地址鏈接。
要想讓這個地址鏈接變好看,而且有利于SEO,我們就要修改它的固定鏈接。在register_post_type()函數中有固定鏈接相關的參數有rewrite和slug,我們要用到這2個參數(詳見上一章的介紹)。出現上圖中這種難看的地址是因爲我們在wordpress後台設置了固定鏈接,而在register_post_type()注冊自定義文章類型時rewrite設置成true,就會是“自定義文章類型名+文章名”的地址,因爲register_post_type()默認展示地址鏈接樣式是‘post-slug/postname’,也就是自定義文章類型名+文章名,所以我們要對它進行修改,也就是修改這個固定鏈接的樣式,如:讓固定鏈接顯示文章的ID号,而不是文章名。如下:
http://xxxxxxxxxx.com/book/33.html
那麽怎樣實現呢?下面這段代碼就是修改自定義文章類型的固定鏈接格式的代碼,将它放到主題的functions.php文件中就可以了:
- 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’ );
- }
效果如下圖:
上面,這段代碼隻适應一個自定義文章類型時可用,如果你注冊了多個自定義文章分類時,就不适用了。方法總比問題多,下面就是解決之道:
- $mytypes = array(
- ‘type1’ => ‘slug1’,
- ‘type2’ => ‘slug2’,
- ‘type3’ => ‘slug3’
- );
- add_filter(‘post_type_link’, ‘custom_book_link’, 1, 3);
- function custom_book_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’, ‘custom_book_rewrites_init’ );
- function custom_book_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’ );
- }
- }
上面的代碼中,有3個自定義文章類型,它們分别是slug1、slug2、slug3,當然,這個名稱要跟你的注冊時原名稱要一至哦,slug1、slug2、slug3分别爲固定鏈接的前綴。
好了,如何修改wordpress自定義文章類型的固定鏈接樣式就講完了,後面還會陸續介紹相關内容。
評論0