問題描述

我正在使用的網站使用以下”pretty” 永久連結結構:

http://example.com/blog/my-special-post

但是對於自定義的帖子型別,我的客戶端希望避免使用”pretty” slug:

http://example.com/product/142

如何使用帖子 ID 代替自定義帖子型別的外掛?

我相信這可能是使用 WP_Rewrite,但我不知道從哪裡開始。

最佳解決方案

這是我用來重寫具有帖子 ID 的自定義帖子型別的 URL 。您需要重寫規則來翻譯 URL 請求,以及 post_type_link 上的過濾器,以便為 get_post_permalink()的任何呼叫返回正確的 URL:

add_filter('post_type_link', 'wpse33551_post_type_link', 1, 3);

function wpse33551_post_type_link( $link, $post = 0 ){
    if ( $post->post_type == 'product' ){
        return home_url( 'product/' . $post->ID );
    } else {
        return $link;
    }
}

add_action( 'init', 'wpse33551_rewrites_init' );

function wpse33551_rewrites_init(){
    add_rewrite_rule(
        'product/([0-9]+)?$',
        'index.php?post_type=product&p=$matches[1]',
        'top' );
}

參考文獻

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