我們通常將WordPress固定鏈接設為/%postname%.html或者/%post_id%.html,可以讓頁面看起來像靜態頁,但當文章有分頁時,分頁鏈接會變得奇怪,比如:
/morning-paper-news.html/3
/132.html/2
html既然是后綴就應該一直在最后,來自solagirl的《用.html作為url后綴時的分頁鏈接問題》一文,為我們提供了解決辦法。
不過原代碼只提供了/%postname%.html的修改方法。
本文提供一下/%post_id%.html的修改方法。
修正WordPress 設置偽靜態后文章分頁鏈接
將下面代碼添加到當前主題 functions.php中:
- // 適合/%post_id%.html分頁鏈接修正
- class Rewrite_Inner_Page_Links_id{
- var $separator;
- function __construct(){
- $this->separator = '/page-';
- if( !is_admin() || defined( 'DOING_AJAX' ) ) :
- add_filter( 'wp_link_pages_link', array( $this, 'inner_page_link_format' ), 10, 2 );
- add_filter( 'get_comments_pagenum_link', array( $this, 'comment_page_link_format' ) );
- add_filter( 'redirect_canonical', array( $this, 'cancel_redirect_for_paged_posts' ), 10, 2 );
- endif;
- if( is_admin() ) :
- add_filter( 'rewrite_rules_array', array( $this, 'pagelink_rewrite_rules' ) );
- register_activation_hook( __FILE__, array( $this, 'flush_rewrite_rules' ) ) ;
- register_deactivation_hook( __FILE__, array( $this, 'flush_rewrite_rules' ) );
- endif;
- }
- function flush_rewrite_rules(){
- flush_rewrite_rules();
- }
- // 修改post分頁鏈接的格式
- function inner_page_link_format( $link, $number ){
- if( $number > 1 ){
- if( preg_match( '%
- $link = preg_replace( "%(/.html)/(/d*)%", $this->separator."$2$1", $link );
- }
- }
- return $link;
- }
- // 為新的鏈接格式增加重定向規則,移除原始分頁鏈接的重定向規則,防止重復收錄
- function pagelink_rewrite_rules( $rules ){
- foreach ($rules as $rule => $rewrite) {
- if ( $rule == '([0-9]+).html(/[0-9]+)?/?$' ) {
- unset($rules[$rule]);
- }
- }
- $new_rule['([0-9]+)('.$this->separator.'([0-9]+))?.html/?$'] = 'index.php?p=$matches[1]&page=$matches[3]';
- return $new_rule + $rules;
- }
- // 禁止WordPress將頁面分頁鏈接跳轉到原來的格式
- function cancel_redirect_for_paged_posts( $redirect_url, $requested_url ){
- global $wp_query;
- if( is_single() && $wp_query->get( 'page' ) > 1 ){
- return false;
- //Vevb.com
- }
- return true;
- }
- }
- new Rewrite_Inner_Page_Links_id();
添加代碼后,需要保存一下固定鏈接設置。之后再次打開文章分頁鏈接,會變成類似的:
/morning-paper-news/page-2.html
/132/page-2.html
注:上述代碼并沒有評論分頁的鏈接修正,本人無此剛需未做研究。
其它固定鏈接形式,需要安裝rewrite rules inspector插件查看鏈接正則寫法并修改上述代碼。
新聞熱點
疑難解答
圖片精選