add_rewrite_rule 可以帮助您嗅探请求,并让您根据需要进行处理。
if( ! class_exists(\'PropertiesEndpoint\')):
class PropertiesEndpoint {
// 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[] = \'__properties\';
$vars[] = \'city\';
$vars[] = \'id\';
return $vars;
}
// Add API Endpoint
public function add_endpoint() {
add_rewrite_rule(\'^properties/([^/]*)/([^/]*)/?\', \'index.php?__properties=1&city=$matches[1]&id=$matches[2]\', \'top\');
add_rewrite_rule(\'^properties/?\', \'index.php?__properties=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[ \'__properties\' ])) {
if(isset($wp->query_vars[ \'city\' ]) && isset($wp->query_vars[ \'id\' ])) {
$this->handle_request__properties_home_for_sale();
die(); // stop default WP behavior
}
else if( isset($wp->query_vars[ \'city\' ]) ) {
// handle in separate file
require_once get_template_directory() . \'/single-properties-in-city.php\';
die(); // stop default WP behavior
}
$this->handle_request__properties();
// continue default WP behavior
}
}
// Handle Requests
protected function handle_request__properties_home_for_sale() {
global $wp;
$city = $wp->query_vars[ \'city\' ];
$id = $wp->query_vars[ \'id\' ];
?>SHOW PROPERTY IN <?php echo $city . \' - \' . $id;
}
protected function handle_request__properties() {
// Control the template used
add_filter(\'template_include\', function ($original_template) {
// change the default template to a google map template
return get_template_directory() . \'/single-properties-google-map.php\';
});
}
}
$propEPT = new PropertiesEndpoint();
$propEPT->init();
endif; // PropertiesEndpoint
Monkeyman Rewrite Analyzer 可以帮助您确保端点正常工作。
<人力资源>
UPDATE
我添加了几种处理请求的方法。您可以通过使用终止进程来忽略默认WP行为
die()
在你处理完之后。或调整模板并继续默认行为
template_include 滤器