問題描述

所以這讓我絕對瘋狂。我花了幾天時間來解決這個問題,我無法解決為什麼這麼困難,因為這是一個非常常見的永久連結結構!

我看了幾百個答案和帖子,沒有一個似乎解決了這個問題。

我只想要這個結構:

mysite.com/custom-post-type/custom-taxonomy-term/post-name

所以我實現如下:

mysite.com/literature - all literature posts
mysite.com/literature/fiction - all literature posts with 'fiction' term
mysite.com/literature/fiction/mybook - the post

每次我嘗試一些東西,我會收到 404 錯誤,或者停止不起作用。

我不明白為什麼這麼難!

任何幫助真的很感激!

謝謝

================================================== ==== ==================附加資訊==================

目前我正在註冊的職位型別和分類如下:

register_post_type('literature',$args);
'rewrite' => array('slug' => 'literature/books','with_front' => false),

register_taxonomy('literature_category',array('literature'), array(
'rewrite' => array( 'slug' => 'literature','with_front' => false ),

如果我同時註冊為’literature’,我將在 mysite.com/literature 頁面上獲得 404,但這顯示了我的永久連結:mysite.com/literature/books/mybook

遵循這個問題的建議 – Custom post types, taxonomies, and permalinks

我已將其新增到我的功能中:

function filter_post_type_link($link, $post) {
    if ($post->post_type != 'literature')
        return $link;

    if ($cats = get_the_terms($post->ID, 'literature_category'))
        $link = str_replace('%literature_category%', array_pop($cats)->slug, $link);
    return $link;
}
add_filter('post_type_link', 'filter_post_type_link', 10, 2);

並將我的帖子型別更改為'slug' => 'literature/%literature_category%'並將我的分類法更改為'slug' => 'literature'

這是非常好的,除了在 mysite.com/literature 分頁不起作用,所以我得到一個 404 錯誤在以下 url:

mysite.com/literature/page/2/

最佳解決方案

按照您已經在 this question 上的建議,但將其新增到您的程式碼中:

add_action( 'generate_rewrite_rules', 'fix_literature_category_pagination' );
function fix_literature_category_pagination( $wp_rewrite ) {
    unset($wp_rewrite->rules['literature/([^/]+)/page/?([0-9]{1,})/?$']);
    $wp_rewrite->rules = array(
        'literature/?$' => $wp_rewrite->index . '?post_type=literature',
        'literature/page/?([0-9]{1,})/?$' => $wp_rewrite->index . '?post_type=literature&paged=' . $wp_rewrite->preg_index( 1 ),
        'literature/([^/]+)/page/?([0-9]{1,})/?$' => $wp_rewrite->index . '?literature_category=' . $wp_rewrite->preg_index( 1 ) . '&paged=' . $wp_rewrite->preg_index( 2 ),
    ) + $wp_rewrite->rules;
}

最後,轉到設定> 固定連結並點選儲存。如果仍然不行,請再次儲存您的永久連結。有時我覺得你必須儲存兩次,但是誰知道。無論如何,讓我知道你如何做出來。請注意,電腦科學標準答案#1 適用:它適用於我…–)

從 TMI 的土地

為了參考,預設情況下頁面不起作用的原因是 WordPress 為文學/%literature_category%/%書%/%頁面%設定了一個重寫規則,如果您考慮到這一點,這是非常有意義的。因此,您的預設固定連結具有以下順序的這些競爭規則:

[literature/([^/]+)/([^/]+)(/[0-9]+)?/?$] => index.php?literature_category=$matches[1]&book=$matches[2]&page=$matches[3]
[literature/([^/]+)/page/?([0-9]{1,})/?$] => index.php?literature_category=$matches[1]&paged=$matches[2]

我們在這裡真正做的是透過取消設定後者來改變它們的順序 (我們可以保留它,但是之後每個重寫都有一個更多的正規表示式在頁面載入上執行),並將其新增到陣列的開頭。

有趣的事實:如果您有一個名為”page” 的”book”,它有多個頁面,則此順序將發生衝突,其後續頁面將不起作用!

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。