問題描述
使用/%category%/%postname%/為固定連結我得到一個 URL 字串的所有類別,特定的帖子被包含在我想要的 url 中的類別被過濾到只有一個分支的類結構,而不是從根父類別。
我有一個旅遊部落格,我有這個類別結構:地方> countryName> regionName> cityName 例如:www.mytravelblog.com/places/indonesia/java/jakarta/myPostName/
我想跳過 URL 中的根類別,或者甚至只使用最小的子例如:www.mytravelblog.com/jakarta/myPostName
可能嗎? (WP 3.0.1)
最佳解決方法
這應該是可能的首先,你很幸運,www.mytravelblog.com/jakarta/myPostName/已經可以工作,它顯示你的帖子,不會重定向到更長的版本 (至少它似乎在我身邊) 。這意味著您只需要處理生成的連結,並不會影響傳入的 URL 處理方式或”canonicalized” 。
要修改的 get_permalink()的結果透過 post_link 進行過濾。所以你可以做這樣的事情:
add_filter( 'post_link', 'remove_parent_cats_from_link', 10, 3 );
function remove_parent_cats_from_link( $permalink, $post, $leavename )
{
$cats = get_the_category( $post->ID );
if ( $cats ) {
// Make sure we use the same start cat as the permalink generator
usort( $cats, '_usort_terms_by_ID' ); // order by ID
$category = $cats[0]->slug;
if ( $parent = $cats[0]->parent ) {
// If there are parent categories, collect them and replace them in the link
$parentcats = get_category_parents( $parent, false, '/', true );
// str_replace() is not the best solution if you can have duplicates:
// myexamplesite.com/luxemburg/luxemburg/ will be stripped down to myexamplesite.com/
// But if you don't expect that, it should work
$permalink = str_replace( $parentcats, '', $permalink );
}
}
return $permalink;
}
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。