您可以使用add_rewrite_rule()
.
我个人喜欢在一个类中展示这个示例,以便为它的复制/粘贴做好准备。您可以将其放入插件或函数中。php——之前加载此代码的某个地方query_vars
, parse_request
和init
.
目标是添加重写规则,确保可以向主查询添加自定义属性,然后用自定义模板替换要加载的默认模板。
if (!class_exists(\'RentsAndCompaniesRewrite\')):
class RentsAndCompaniesRewrite
{
// 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[] = \'show_companies\';
$vars[] = \'show_rents\';
$vars[] = \'location\';
return $vars;
}
// Add API Endpoint
public function add_endpoint()
{
add_rewrite_rule(\'^rents/([^/]*)/?\', \'index.php?show_rents=1&location=$matches[1]\', \'top\');
add_rewrite_rule(\'^companies/([^/]*)/?\', \'index.php?show_companies=1&location=$matches[1]\', \'top\');
flush_rewrite_rules(false); //// <---------- REMOVE THIS WHEN DONE TESTING
}
// Sniff Requests
public function sniff_requests($wp_query) {
global $wp;
if ( isset( $wp->query_vars[ \'show_rents\' ], $wp->query_vars[ \'location\' ] ) ) {
$this->handle_request_show_rents();
} else if ( isset( $wp->query_vars[ \'show_companies\' ], $wp->query_vars[ \'location\' ] ) ) {
$this->handle_request_show_companies();
}
}
// Handle Requests
protected function handle_request_show_rents()
{
add_filter(\'template_include\', function ($original_template) {
return get_stylesheet_directory() . \'/templates/rents_by_location.php\';
});
}
protected function handle_request_show_companies()
{
add_filter(\'template_include\', function ($original_template) {
return get_stylesheet_directory() . \'/templates/companies_by_location.php\';
});
}
}
$wptept = new RentsAndCompaniesRewrite();
$wptept->init();
endif; // RentsAndCompaniesRewrite
在主题内的目录中,添加处理请求时将使用的模板。
/templates/companies_by_location.php
<?php
global $wp;
$location = $wp->query_vars[ \'location\' ];
echo \'Companies in the \' . $location . \' area:\';
/templates/rents_by_location.php
<?php
global $wp;
$location = $wp->query_vars[ \'location\' ];
echo \'Rents in the \' . $location . \' area:\';