Wordpress重写规则和url中的自定义可选参数

时间:2014-03-13 20:25:50

标签: php regex wordpress url-rewriting rewrite

我正在尝试使用add_rewrite_rules为Wordpress网站构建过滤功能。我有以下链接示例

 example.com/offers-type-all-inclusive-from-germany-transportation-airplane.html

使用以下重写规则:

add_rewrite_rule('^offers-type-?([a-z0-9-]+)?-from-?([a-z-]+)?-transportation-?([a-z0-9-]+)?.html','index.php?filters=offers&type=$matches[1]&location=$matches[2]&transportation=$matches[3]','top');

我设法将用户重定向到自定义页面模板,参数存储为数组

array(
    'type' => 'all-inclusive',
    'from' => 'germany',
    'transportation' => 'airplane'
     );

问题是某些参数可以是可选的,所以像

这样的链接
example.com/offers-type-all-inclusive-from-germany.html
example.com/offers-type-all-inclusive-transportation-airplane.html

还需要构建正确的过滤数组。

甚至有可能实现这一目标吗?

1 个答案:

答案 0 :(得分:2)

真是一个棘手的正则表达式!

试试这个表达式

offers-type-([a-z0-9-]*?)(?:-from-([a-z-]*?))?(?:-transportation-([a-z0-9-]*?))?\.html

这是在线演示

http://regex101.com/r/fS4xB7

相关问题