使用add_rewrite_rule
捕获url并在内部转换为参数。
http://example.com/page{p}/t/{t}
to
http://example.com/?p={p}&t={t}
添加到您的函数中。php或插件。
<?php
if ( ! class_exists( \'SimpleRewrite\' ) ):
class SimpleRewrite {
const ENDPOINT_QUERY_NAME = \'page\';
const ENDPOINT_QUERY_PARAM = \'__rewrite_page\';
// WordPress hooks
public function init() {
add_filter( \'query_vars\', array ( $this, \'add_query_vars\' ), 0 );
add_action( \'parse_request\', array ( $this, \'sniff_requests\' ), 0 );
add_action( \'init\', array ( $this, \'add_endpoint\' ), 0 );
}
// Add public query vars
public function add_query_vars( $vars ) {
// add all the things we know we\'ll use
$vars[] = static::ENDPOINT_QUERY_PARAM;
$vars[] = \'p\';
$vars[] = \'t\';
return $vars;
}
// Add API Endpoint
public function add_endpoint() {
add_rewrite_rule( \'^\' . static::ENDPOINT_QUERY_NAME . \'([^/]*)/t/([^/]*)/?\', \'index.php?\' . static::ENDPOINT_QUERY_PARAM . \'=1&p=$matches[1]&t=$matches[2]\', \'top\' );
//////////////////////////////////
flush_rewrite_rules( false ); //// <---------- REMOVE THIS WHEN DONE
//////////////////////////////////
}
// Sniff Requests
public function sniff_requests( $wp_query ) {
global $wp;
if ( isset(
$wp->query_vars[ static::ENDPOINT_QUERY_PARAM ],
$wp->query_vars[ \'p\' ],
$wp->query_vars[ \'t\' ] ) ) {
$this->handle_request(); // handle it
}
}
// Handle Requests
protected function handle_request() {
global $wp;
$page = $wp->query_vars[ \'p\' ];
$t = $wp->query_vars[ \'t\' ];
add_filter( \'template_include\', function( $original_template ) {
return __DIR__ . \'/custom.php\';
} );
}
}
$wpSimpleRewrite = new SimpleRewrite();
$wpSimpleRewrite->init();
endif; // SimpleRewrite
将参数限制为仅数字“
\\d
“将重写匹配更改为:
\'^\' . static::ENDPOINT_QUERY_NAME . \'(\\d*)/t/(\\d*)/?\'