如何使用generate_rewrite_rules在WordPress插件中为索引添加路由?

时间:2018-10-01 20:47:17

标签: php wordpress

我正在尝试在插件中将路由/.well-known/webfinger添加到WordPress,例如http://exampleblog.com/.well-known/webfinger。我正在使用generate_rewrite_rulesparse_requestquery_vars挂钩来加载一些在URL匹配时应运行的代码。这就是我所拥有的:

// includes/server/api.php
namespace api;

function generate_rewrite_rules( $wp_rewrite ) {
    $dot_well_known = array(
        '.well-known/webfinger' => 'index.php?well-known=webfinger'
    );
    $wp_rewrite->rules = $dot_well_known + $wp_rewrite->rules;
}

function check_flush_rules() {
    $rules = get_option( 'rewrite_rules' );
    if ( ! isset( $rules['.well-known/webfinger'] ) ) {
        global $wp_rewrite;
        $wp_rewrite->flush_rules();
    }
}

function parse_request( $req ) {
    if ( ! array_key_exists( 'well-known', $req->query_vars ) ) {
        return;
    }
    if ( $req->query_vars['well-known'] === 'webfinger' ) {
        do_action( 'well_known_webfinger', $req->query_vars );
    }
}

function query_vars( $query_vars ) {
    $query_vars[] = 'well-known';
    return $query_vars;
}

// includes/init.php
namespace init;

require_once plugin_dir_path( __FILE__ ) . 'server/api.php';

add_action( 'my_plugin_load', function() {
    add_action( 'generate_rewrite_rules', '\api\generate_rewrite_rules' );
    add_action( 'parse_request', '\api\parse_request' );
    add_filter( 'query_vars', '\api\query_vars' );
    \api\check_flush_rules();
} );

// my_plugin.php (plugin entrypoint)
require_once plugin_dir_path( __FILE__ ) . 'includes/init.php';

function my_plugin_load() {
    do_action( 'my_plugin_load' );
}

add_action( 'plugins_loaded', 'my_plugin_load' );

但是,当我运行本地WordPress实例时(通过php -S localhost:8080),当我尝试访问404 Not Found时,我的状态为http://localhost:8080/.well-known/webfinger

我在做什么错了?

1 个答案:

答案 0 :(得分:0)

事实证明,问题是我通过php -S localhost:8080运行WordPress。当我在本地运行适当的Apache网络服务器时,generate_rewrite_rules可以正常工作。