問題描述

有沒有辦法將.html 擴展添加到自定義帖子類型沒有插件?

對於帖子我可以使用/%postname.html 在永久鏈接設置

對於我可以使用的頁面:

add_action('init', 'change_page_permalink', -1);
function change_page_permalink() {
    global $wp_rewrite;
    if ( strstr($wp_rewrite->get_page_permastruct(), '.html') != '.html' )
        $wp_rewrite->page_structure = $wp_rewrite->page_structure . '.html';
}

自定義帖子類型?

有沒有一些類似於上述的代碼,可以讓我改變或添加.html 在自定義帖子類型的 url?

最佳解決方案

這似乎工作:

創建重寫規則,如 post-type/post-name.html 。您可以使用數組為僅僅一些帖子類型創建規則,而不是為其創建所有這些規則。

add_action( 'rewrite_rules_array', 'rewrite_rules' );
function rewrite_rules( $rules ) {
    $new_rules = array();
    foreach ( get_post_types() as $t )
        $new_rules[ $t . '/([^/]+).html$' ] = 'index.php?post_type=' . $t . '&name=$matches[1]';
    return $new_rules + $rules;
}

格式化這些帖子類型的新固定鏈接結構。

add_filter( 'post_type_link', 'custom_post_permalink' ); // for cpt post_type_link (rather than post_link)
function custom_post_permalink ( $post_link ) {
    global $post;
    $type = get_post_type( $post->ID );
    return home_url( $type . '/' . $post->post_name . '.html' );
}

然後停止重定向規範網址以刪除尾部斜線。這可能需要更多的工作,因為您可能希望在大多數情況下保持重定向。

add_filter( 'redirect_canonical', '__return_false' );

正如其他人在這裏説的,在完成上述之後,您需要刷新規則,這可以通過訪問 Dashboard -> Settings -> Permalinks 中的 options-permalink.php 管理頁面進行。

次佳解決方案

您可以為此替代替代內置固定鏈接的重寫規則,例如為自定義帖子類型”product” …

add_action('init', 'add_html_ext_to_custom_post_types');
function add_html_ext_to_custom_post_types() {
    add_rewrite_rule('^product/([^/]+).html', 'index.php?product=$matches[1]', 'top');
}

(不要忘了用 re-saving 您的固定鏈接或使用 flush_rules 以上述方式刷新您的規則) 。

Caveats

  • 我不認為像 the_permalink()這樣的功能會使用它,所以你可能需要為 post_link 添加一個過濾器來捕獲這些鏈接。您還可以添加到 redirect_canonical 過濾器以重定向默認固定鏈接,以便/product /foo 和/product /foo /redirect 重定向到/product/foo.html 。

  • 您需要為您網站使用的其他網址添加附加重寫,例如 feed URL,後續頁面,trackbacks 等。上面的代碼將適用於主要的自定義帖子類型頁面。

參考文獻

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