問題描述

我有一個自定義的職位型別的投資組合 (slug 投資組合) 在我的主題,一切正常工作,除了一件事情。當人們建立一個包含投資組合的頁面時,例如:example.com/portfolio,該主題認為我想使用自定義帖子型別歸檔頁面,而不是我在編輯器中建立的頁面。

我可以以某種方式”reserve” 在儲存頁面以確保它永遠不會被使用時,可以將其重新命名為 portfolio-page?

我的專案使用本教程中概述的方法,這裡是我所指的衝突:

“Beyond having to patch the code there is one other catch here in that you can』t call your Page slug the same thing as your custom post type slug. Think of your custom post type slug as a reserved keyword; however, you can make the title of your Page the same name as your custom post type slug just as long as your Page slug is something different.” – http://wp.tutsplus.com/tutorials/custom-post-type-pagination-chaining-method/

感謝任何建議!

最佳解決方案

以下 2 個過濾器允許您在 WordPress 檢查 slug 並在 wp-includes /post.php 檔案中的功能 wp_unique_post_slug() 中找到。

有 2 個過濾器,一個用於分層職位,一個用於 non-hierarchical 。分層過濾器為帖子父級提供 ID,因此,如果 $ post_parent 為 0,則您知道這是一個”base” 帖子。

如果您想要將特定的帖子型別新增到邏輯中,那麼過濾器也會傳遞 $ post_type 。

透過返回”true”,你告訴 WordPress 這個 s 子是壞的,所以 WordPress 新增一個字尾,就像它會做,如果你試圖給我們一個已經採取的郵政名稱/s 子。

add_filter( 'wp_unique_post_slug_is_bad_hierarchical_slug', 'portfolio_is_bad_hierarchical_slug', 10, 4 );
function portfolio_is_bad_hierarchical_slug( $is_bad_hierarchical_slug, $slug, $post_type, $post_parent ) {
    if ( !$post_parent && $slug == 'portfolio' )
        return true;
    return $is_bad_hierarchical_slug;
}

add_filter( 'wp_unique_post_slug_is_bad_flat_slug', 'portfolio_is_bad_flat_slug', 10, 3 );
function portfolio_is_bad_flat_slug( $is_bad_flat_slug, $slug, $post_type ) {
    if ( $slug == 'portfolio' )
        return true;
    return $is_bad_flat_slug;
}

參考文獻

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