add_action('init','codex_custom_init');functioncodex_custom_init(){$labels=array('name'=>_x('Books','posttypegeneralname'),'singular_name'=>_x('Book','posttypesingularname'),'add_new'=>_x('AddNew','book'),'add_new_item'=>__('AddNewBook'),'edit_item'=>__('EditBook'),'new_item'=>__('NewBook'),'all_items'=>__('AllBooks'),'view_item'=>__('ViewBook'),'search_items'=>__('SearchBooks'),'not_found'=>__('Nobooksfound'),'not_found_in_trash'=>__('NobooksfoundinTrash'),'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);}自定義文章類型的默認固定鏈接格式CustomPostType默認的固定鏈接格式是‘post-slug/postname’,如果沒有指定slug,則用posttype作為slug,本例中沒有指定,所有postslug就是book。
與固定鏈接相關的參數有rewrite、和slugrewrite參數指定是否開啟固定鏈接功能,rewrite默認是true,如果設置成false,假設我創建了一個book類型的文章,標題是“HarryPotterBook”,產生的鏈接如下:結尾是否有反斜杠,取決于設置-固定鏈接中的格式結尾是否有反斜杠,建議這里結尾不要帶反斜杠,否則可能出現指向同一個地址的情況,對搜索引擎不友好。
如何修改自定義文章類型的固定鏈接格式假設我們創建了book類型的文章,并且用中文當做文章標題,那么默認產生的鏈接也將是中文,中文鏈接通常會編碼,比較長,分享不方便。
你可以手動輸入英文slug,也可以通過修改固定鏈接格式讓了鏈接更簡短。
要達到這個目的:創建新的rewrite規則翻譯URL添加filter(post_type_link),當get_the_permalink()函數調用時,返回正確的鏈接格式下面有兩段代碼,都可以實現這個要求,代碼加到*中,并且要到后臺-設置-固定鏈接中重新保存固定鏈接,代碼才能生效。
代碼段1add_action('init','custom_book_rewrite');functioncustom_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);functioncustom_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;}}
轉載請注明出處華閱文章網 » 電腦里自定義課程怎樣導入散文