可以在WordPress中使用add_rewrite_rule()
.
把这个放进去functions.php 或aplugin. 它比简单的ReWriteRule
但在WordPress方面,您将有更多的灵活性和控制力。
<?php
if ( ! class_exists( \'ExamRewrite\' ) ):
class ExamRewrite {
const ENDPOINT_QUERY_PARAM = \'__redirect_exam\';
// 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 ) {
$vars[] = static::ENDPOINT_QUERY_PARAM;
$vars[] = \'get\';
$vars[] = \'exam\';
return $vars;
}
// Add Endpoint
public function add_endpoint() {
add_rewrite_rule( \'^example/(exam1|exam2)\', \'index.php?\' . static::ENDPOINT_QUERY_PARAM . \'=1&exam=$matches[1]\', \'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[ \'get\' ] ) ) {
$get = $wp->query_vars[ \'get\' ];
$exam = $wp->query_vars[ \'exam\' ];
$new_url = site_url( "/$get/$exam" );
wp_safe_redirect( $new_url, 301 );
die();
}
}
}
$wpExamRewrite = new ExamRewrite();
$wpExamRewrite->init();
endif; // ExamRewrite