在WordPress自定义插件中添加重写规则

在WordPress自定义插件中添加重写规则,wordpress,url-rewriting,Wordpress,Url Rewriting,我尝试在my pugin 当我使用我的自定义页面,我会像下面的url http://localhost/wordpress/wp-content/plugins/my-plugin/testurl.php 但是我想要这个 http://localhost/wordpress/testurl 我在插件中编写了这段代码 function create_rewrite_rules($rules) { //print_r($rules); global $wp_rew

我尝试在
my pugin

当我使用我的自定义页面,我会像下面的url

http://localhost/wordpress/wp-content/plugins/my-plugin/testurl.php
但是我想要这个

http://localhost/wordpress/testurl
我在插件中编写了这段代码

function create_rewrite_rules($rules) {
        //print_r($rules);
        global $wp_rewrite;
        $newRule = array('/testurl' => 'wp-content/plugins/my-plugin/testurl.php');
        //echo $newRule;
        $newRules = $newRule + $rules;
        //$newRules = $newRule;
        // echo "<pre>";
        // print_r($newRules);
        return $newRules;
    }

    function flush_rewrite_rules() {
        //echo 1;
        global $wp_rewrite;
        $wp_rewrite->flush_rules();
    }

if(class_exists('MyPlugin'))
    $myPlugin = new MyPlugin();

add_filter('rewrite_rules_array', array($myPlugin, 'create_rewrite_rules'));
add_filter('init', array($myPlugin, 'flush_rewrite_rules'));
函数创建\重写\规则($rules){
//打印(规则);
全球$wp_重写;
$newRule=array('/testurl'=>'wp-content/plugins/my-plugin/testurl.php');
//echo$newRule;
$newRules=$newRule+$rules;
//$newRules=$newRule;
//回声“;
<?php
/*
Plugin Name: Rewrite test
*/

function custom_rewrite_basic() {
    add_rewrite_rule('^testurl?', 'wp-content/plugins/my-plugin/testurl.php', 'top');
}

register_deactivation_hook( __FILE__, 'flush_rewrite_rules' );
register_activation_hook( __FILE__, 'myplugin_flush_rewrites' );
function myplugin_flush_rewrites() {
    custom_rewrite_basic();
    flush_rewrite_rules();
}
//打印规则($newRules); 返回$newRules; } 函数flush\u rewrite\u rules(){ //回声1; 全球$wp_重写; $wp_rewrite->flush_rules(); } 如果(类_存在('MyPlugin')) $myPlugin=新的myPlugin(); 添加过滤器('rewrite_rules_array',array($myPlugin,'create_rewrite_rules')); 添加过滤器('init',数组($myPlugin,'flush_rewrite_rules');

但是这没办法。

有几件事你必须注意:

  • 您必须仅在插件激活/停用时刷新重写规则,而不是在初始化时刷新重写规则,以防止性能问题
  • rewrite\u规则
    第一个参数必须是正则表达式
  • init
    hook是一个动作,而不是过滤器
下面的插件代码确实有效:


你好,我还有几个问题吗?