html固定链接#,WordPress固定链接用.html后缀时的分页处理方法

这个博客内容涉及WordPress中的URL重写,通过Rewrite_Inner_Page_Links类实现内页和评论分页链接的格式修改。类中定义了构造函数、正则表达式和过滤器,用于在非后台环境中改变分页链接结构,防止重定向到原始格式,避免搜索引擎重复收录。同时,它还添加了重定向规则,确保访问旧链接时返回404状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

classRewrite_Inner_Page_Links{

var$separator;

var$post_rule;

var$comment_rule;

function__construct(){

$this->separator = '/page-';

$this->post_rule = 'archives/([^/]+)('.$this->separator.'([0-9]+))?.html/?$';

$this->comment_rule = 'archives/([^/]+)/comment-page-([0-9]{1,}).html(\#[^\s])?$';

if( !is_admin() || defined( 'DOING_AJAX' ) ) :

add_filter( 'wp_link_pages_link', array( $this, 'inner_page_link_format' ), 10, 2); // for inner pages

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' ) );

endif;

}

/**

* 修改post分页链接的格式

* @param string $link

* @param int $number

* @return string

*/

functioninner_page_link_format( $link, $number ){

if( $number > 1){

if( preg_match( '%

$link = preg_replace( "%(\.html)/(\d*)%", $this->separator."$2$1", $link );

}

}

return$link;

}

/**

* 修改评论分页链接

* @param string $result

* @return string

*/

functioncomment_page_link_format( $result ){

// From hello-world.html/comment-page-1#comments to hello-world/comment-page-1.html#comments

if( strpos( $result, '.html/' ) !== false){

$result = preg_replace( '=([^/]+)(.html)/comment-page-([0-9]{1,})=', "$1/comment-page-$3$2" ,$result );

}

return$result;

}

/**

* 为新的链接格式增加重定向规则,移除原始分页链接的重定向规则,防止重复收录

*

* 访问原始链接将返回404

* @param array $rules

* @return array

*/

functionpagelink_rewrite_rules( $rules ){

foreach ($rules as $rule => $rewrite) {

if( $rule == '([^/]+).html(/[0-9]+)?/?$' || $rule == '([^/]+).html/comment-page-([0-9]{1,})/?$' ) {

unset($rules[$rule]);

}

}

$new_rule[ $this->post_rule ] = 'index.php?name=$matches[1]&page=$matches[3]';

$new_rule[ $this->comment_rule ] = 'index.php?name=$matches[1]&cpage=$matches[2]';

return$new_rule + $rules;

}

/**

* 禁止WordPress将页面分页链接跳转到原来的格式

* @param string $redirect_url

* @param string $requested_url

* @return bool

*/

functioncancel_redirect_for_paged_posts( $redirect_url, $requested_url ){

global$wp_query;

if( is_single() && $wp_query->get( 'page' ) > 1){

return false;

}

return true;

}

}

newRewrite_Inner_Page_Links();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值