[英]Getting WordPress to automatically show category permalink for only specific categories
您只需通過“設置”>“永久鏈接”並將“ /blog/%postname%/
添加到“通用設置”>“自定義結構”即可。 在那里,您可以從www.site.com/blog/title獲得博客文章。
我不明白第一個問題。 通過:
我希望大多數帖子在URL中都沒有類別
您是說不擁有www.site.com/category/category-name嗎? 還是沒有www.site.com/category/post?
編輯#1
要回答這個問題:
我只希望www.site.com/category/post類別為“博客”的博客帖子>如果類別為“鞋子”,我不希望該類別顯示在URL中。 –
首先:您可以將永久鏈接設置為/%postname%/
這樣您的所有帖子都將具有網站/標題,因此可以從該鏈接訪問
第二:您必須過濾永久鏈接,以使“博客”類別下的帖子的行為有所不同。
嘗試這個
add_filter( 'post_link', 'custom_permalink', 10, 2 );
function custom_permalink( $permalink, $post ) {
// Get the categories for the post
$categories = wp_get_post_categories( $post->ID );
foreach ( $categories as $cat ) {
$post_cat = get_category( $cat );
$post_cats[] = $post_cat->slug;
}
// Check if the post have 'blog' category
// Assuming that your 'Blog' category slug is 'blog'
// Change 'blog' to match yours
if ( in_array( 'blog',$post_cats ) ) {
$permalink = trailingslashit( home_url( 'blog/' . $post->post_name ) );
}
return $permalink;
}
第三:您必須過濾rewrite_rules
add_filter( 'rewrite_rules_array', 'custom_rewrite_rule' );
function custom_rewrite_rule( $rules ) {
$new_rules = array(
'blog/([^/]+)/trackback/?$' => 'index.php?name=$matches[1]&tb=1',
'blog/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?name=$matches[1]&feed=$matches[2]',
'blog/([^/]+)/(feed|rdf|rss|rss2|atom)/?$' => 'index.php?name=$matches[1]&feed=$matches[2]',
'blog/([^/]+)/comment-page-([0-9]{1,})/?$' => 'index.php?name=$matches[1]&cpage=$matches[2]',
'blog/([^/]+)(/[0-9]+)?/?$' => 'index.php?name=$matches[1]&page=$matches[2]'
);
$rules = $new_rules + $rules;
return $rules;
}
轉到永久鏈接設置並保存設置以刷新您的重寫規則並使上述更改生效
注意:在活動主題functions.php
模板上添加這些功能
注意:我尚未測試,但這是您更改固定鏈接的方式。 我以類似的方式更改了檔案和搜索結果的永久鏈接。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.