問題描述
我無法使用 WordPress 重寫規則,並可以使用一些幫助。
我有一個名為_shows_
的自定義帖子類型。
所有節目都有一個自定義分類類別_show-category_.
A _show_
將永遠不會有多個_show-category_
。
我希望我的 URL 以這種方式路由:
www.mysite.com/shows/ => archive-shows.php
www.mysite.com/shows/%category%/ => taxonomy-show-category.php
www.mysite.com/shows/%category%/%postname%/ => single-shows.php
所以作為一個現實世界的例子,讓我們説一個_show-category_
“Foo” 和一個_show_
的標題為”Bar” 的帖子,它具有”Foo”,因為它是_show-category_
。我會期望我的 WordPress 應用程序看起來像這樣:
www.mysite.com/shows/foo/ => shows all posts under the foo category
www.mysite.com/shows/foo/bar => shows the indivual post
我儘可能避免插件,但是對任何解決方案都是開放的。
最佳解決方案
首先,register your taxonomy 將 rewrite
的 slug
參數設置為 shows
:
register_taxonomy(
'show_category',
'show',
array(
'rewrite' => array( 'slug' => 'shows', 'with_front' => false ),
// your other args...
)
);
接下來,將 register your post type 設置為 shows/%show_category%
,並將 has_archive
參數設置為 shows
:
register_post_type(
'show',
array(
'rewrite' => array( 'slug' => 'shows/%show_category%', 'with_front' => false ),
'has_archive' => 'shows',
// your other args...
)
);
最後,在 post_type_link
中添加一個過濾器來替換個人展示永久鏈接中的節目類別:
function wpa_show_permalinks( $post_link, $post ){
if ( is_object( $post ) && $post->post_type == 'show' ){
$terms = wp_get_object_terms( $post->ID, 'show_category' );
if( $terms ){
return str_replace( '%show_category%' , $terms[0]->slug , $post_link );
}
}
return $post_link;
}
add_filter( 'post_type_link', 'wpa_show_permalinks', 1, 2 );
編輯
忘了 has_archive
的 register_post_type
參數,應該設置為 shows
。
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。