問題描述
有沒有辦法將.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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。