我正在尝试向基于WordPress的网站添加自定义URL结构。
例如:
example.com/machines //list all machines in a table
example.com/machines?some=params //list filtered machines in a table
example.com/machines/1 //show single machine
数据将来自我已经通过curl开发的外部api。
我无法将数据导入自定义帖子类型,因为它已在许多表上进行了规范化,业务逻辑很复杂,而且无论如何其他设备都使用了api。
我已经看过add_rewrite_rule的文档,但是第二个参数让我感到困惑:
$redirect
(string) (required) The URL you would like to actually fetch
好吧,我没有要提取的网址,我想运行一个函数,它将充当一个简单的路由器-提取网址部分,调用外部api并返回包含正确数据的模板。
调用API很简单,但是我如何将url实际路由到该函数,以及随后如何加载模板(利用现有的WordPress header.php和footer.php)却让我感到困惑。
第一步是用于add_rewrite_endpoint
创建将映射到查询变量的基本URL:
add_action( 'init', function(){
add_rewrite_endpoint( 'machines', EP_ROOT );
} );
在访问固定链接页面刷新重写规则之后,下一步是挂钩到该动作'template_redirect'
,当到达URL时实际执行某些操作:
add_action( 'template_redirect', function(){
if($machinesUrl = get_query_var('machines')){
//var_dump($machinesUrl, $_GET);
//$machinesURl contains the url part after example.com/machines
//eg if url is example.com/machines/some/thing/else
//then $machinesUrl == 'some/thing/else'
//and params can be got at simply via $_GET
//after parsing url and calling api, its just a matter of loading a template:
locate_template( 'singe-machine.php', TRUE, TRUE );
//then stop processing
die();
}
});
要做的另一件事是处理网址的匹配,而网址没有其他部分,例如example.com/machines
。事实证明,在某些情况下会带有wordpress胆量,空字符串被评估为false,因此被跳过,因此最后一步是连接到过滤器'request'
并设置默认值:
add_filter( 'request', function($vars=[]){
if(isset ( $vars['machines'] ) && empty ( $vars['machines'] )){
$vars['machines'] = 'default';
}
return $vars;
});
通过将它们全部包装在一个或多个类中,可以很容易地改善它。可以将url解析和模板加载逻辑传递到基本路由器,甚至是基本的MVC设置,从文件加载路由等,但是在此之上是起点
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句