php PHP重写规则 - 修复与CPT重写Slug相同的Slug分页

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php PHP重写规则 - 修复与CPT重写Slug相同的Slug分页相关的知识,希望对你有一定的参考价值。

<?php // Don't copy this line...

/**
 * This function will Kill 'blogs/editor' rewrite rules
 * to fix the broken pagination issue on this page:
 * '/blogs/editor/'
 *
 * This fix was needed because we add rewrite rules for CPT: editor
 * And because '/blogs/editor/' is also a static page, the pagination
 * on that page e.g., '/blogs/editor/page/4/' was broken. 
 *
 * What I did here is to change priority of rewrite rules served
 * by WordPress so my custom rewrite rule takes precedence over 
 * other rules. 
 * 
 * To get it to work:
 * 
 * $cpt_slug     = CPT slug.
 * $rewrite_slug = rewrite slug of the conflicting CPT and page. 
 * 
 * Author: Zeshan Ahmed @zeshanshani22
 * Author URI: https://zeshanahmed.com/
 */
add_filter('rewrite_rules_array', 'za_kill_blogs_editor_rules');
function za_kill_blogs_editor_rules( $rules ) {
  $cpt_slug = 'editor';
  $rewrite_slug = 'blogs/editor';

  $blog_editor_rules = [
    // Fix page archives
    "{$rewrite_slug}/page/?([0-9]{1,})/?$" => "index.php?pagename={$rewrite_slug}&paged=$matches[1]", // My custom rule. Added first so it takes precedence
    "{$rewrite_slug}/([^/]+)(?:/([0-9]+))?/?$" => "index.php?$cpt_slug=$matches[1]&page=$matches[2]" // Original rule that we need to kill
  ];

  foreach ( $rules as $rule => $rewrite ) {
    // Killing the original rule here after matching it. 
    if ( false !== strpos( $rule, "{$rewrite_slug}/([^/]+)(?:/([0-9]+))?/?$" )  ) {
      unset( $rules[ $rule ] ); 
    }
  }

  $rules = array_merge( $blog_editor_rules, $rules );

  return $rules;
}

以上是关于php PHP重写规则 - 修复与CPT重写Slug相同的Slug分页的主要内容,如果未能解决你的问题,请参考以下文章

PHP/Apache:用 .htaccess 重写规则

PHP中查询字符串的HTACCESS重写规则

php重写路由

重写规则使目录url结构加载php页面?

php 一个示例插件,显示如何向WordPress添加自定义查询变量,重写标记和重写规则

php 重置重写规则