regex - 带有 add_rewrite_rule 和正则表达式的 Wordpress 映射
问题描述
我被困在我在 wordpress 中的映射。
我有三个add_rewrite_rule()
功能:
(1)
add_rewrite_rule('products[\/](.+)[\/]?$', 'index.php?range=$matches[1]', 'top');
add_filter(
'query_vars',
static function ($query_vars) {
$query_vars[] = 'range';
return $query_vars;
}
);
add_filter(
'template_include',
static function ($template) {
$range = get_query_var('range');
if ($range) {
return __DIR__ . '/range.php';
}
return $template;
}
);
(2)
add_rewrite_rule('product[\/](.+)[\/]product][-]page[\/][\?]code=(.+)$', 'index.php?rangeofproduct=$matches[1]&code=$matches[2]', top');
add_filter(
'query_vars',
static function ($query_vars) {
$query_vars[] = 'rangeofproduct';
return $query_vars;
}
);
add_filter(
'query_vars',
static function ($query_vars) {
$query_vars[] = 'code';
return $query_vars;
}
);
add_filter(
'template_include',
static function ($template) {
$varCode = get_query_var('code');
if ($varCode) {
return __DIR__ . '/product-page.php';
}
return $template;
}
);
(3)
add_rewrite_rule('/products[/](.+)[/](.+)[/]$', 'index.php?productsrange=$matches[1]&family=$matches[2]', 'top');
add_filter(
'query_vars',
static function ($query_vars) {
$query_vars[] = 'productsrange';
return $query_vars;
}
);
add_filter(
'query_vars',
static function ($query_vars) {
$query_vars[] = 'family';
return $query_vars;
}
);
add_filter(
'template_include',
static function ($template) {
$varHttpName = get_query_var('family');
if ($varHttpName) {
return __DIR__ . '/family.php/';
}
return $template;
}
);
对于第一个,我想在http://example.com/products/led/、http://example.com/products/halogen/或httprange
等链接中捕获占位符(根据不同的灯光范围而有所不同)://example.com/products/fluorescent/。
使用第二条规则,我想捕获占位符rangeofproduct
,code
如http://example.com/products/led/?code=123456789。问题从这里开始。rangeofproduct
占位符永远不会获得任何价值。占位range
符仍然如此(我不知道为什么!)。所以我可以用这个。它映射得很好,因为我将映射与$varCode
.
第三条规则可能是最具挑战性的。似乎第一条规则优先并立即采用如下链接:http ://example.com/products/led/a60-standard-led/ 。我上网到https://regexr.com/并且确实第一条规则中的 (.+) 对于'led/a60-standard-led'
.
有人可以帮我吗?
问题是:
(1) 我是否需要在占位符中为同一事物使用不同的名称 ( range
, rangeofproduct
, productsrange
)。
(2)为什么rangeofproduct
不进入$query_vars
?
(3) 如果我matches[1]
在所有三个规则中都使用是否可以,或者我应该在第一条规则matches[1]
中使用,在第二条规则matches[2]
中matches[3]
,最后在第三条规则中matches[4]
使用matches[5]
?
(4) 我应该如何编写将'led/a60-standard-led'
在第一条规则中排除的正则表达式。我试图在正则表达式中找到解决方案:匹配除特定模式之外的所有内容(包含特定文本的字符串(例如,不匹配具有 foo 的字符串)部分)。但是我对正则表达式的了解还不够基础,所以我无法将解决方案适应我的情况,'led/a60-standard-led'
排除'/'
中间。
我最希望的答案是第四个问题的答案。
解决方案
推荐阅读
- sql - 如何首先将输入插入到 sql 表代码中
- javascript - JS 代码在 Google Tag Manager 中生成错误
- javascript - 填充猫鼬查询时展平多个字段
- python - Can't decompress with GZIP: Traceback error
- django - Django Datetime function
- angular - Angular accessing child object in dictionary
- ios - ARKit - Capture textures for provided environment mesh using Lidar
- javascript - How do I make it so when I hover over my text it changes color and the color stays changed?
- c++ - 字符串 Rev 函数,越界异常的奇怪行为 (c++)
- wpf - 如何在 WPF 中仅向特定一侧添加阴影?