阿里云服务器2核2G3M仅需99元/年,续费同价华纳云香港服务器

修正WordPress设置伪静态后文章分页链接问题

WordPress主题推荐

我们通常将 WordPress 固定链接设为 /%postname%.html 或者/%post_id%.html,这样可以让页面看起来像静态页,但当文章有分页时,分页链接会变得奇怪,比如:

  • /morning-paper-news.html/3
  • /132.html/2

html 既然是后缀就应该一直在最后,来自solagirl的《用.html作为url后缀时的分页链接问题》一文,为我们提供了解决办法。不过原代码只提供了 /%postname%.html 的修改方法,本文就补充完善一下,提供一下 /%post_id%.html 的修改方法。具体做法也很简单,只需要将以下代码添加到当前主题 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( '%<a href=".*\.html/\d*"%', $link ) ){
$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;
}
return true;
}
}
new Rewrite_Inner_Page_Links_id();

添加代码后,需要到后台 – 设置 – 固定链接中保存一下设置,之后再次打开文章分页链接,就会变成类似的:

  • /morning-paper-news/page-2.html
  • /132/page-2.html

注:上述代码并没有评论分页的链接修正,本人无此刚需未做研究。其它固定链接形式,需要安装 rewrite rules inspector 插件查看链接正则写法并修改上述代码。

上述代码会与《如何实现WordPress分类目录和页面链接地址以斜杠/结尾》代码冲突,解决办法有待研究。
赞 (0) 打赏
版权声明:本文为转载文章,来源于 知更鸟 ,版权归原作者所有!发布此文是出于传递更多信息之目的,若有来源标注错误或侵犯了您的合法权益,请联系我们,确认后马上更正或删除,谢谢!
wu