我的wordpress插件中包含以下代码,用于添加自定义url重写:
add_action(\'init\', function() {
add_rewrite_rule( \'^cities/(.*)/browse/(.*)/(.*)/(.*)/(.*)\',
\'index.php?city_name=$matches[1]&cat_name[]=$matches[2]&cat_name[]=$matches[3]&cat_name[]=$matches[4]&cat_name[]=$matches[5]\',
\'top\' );
add_rewrite_rule( \'^cities/(.*)/browse/(.*)/(.*)/(.*)\',
\'index.php?city_name=$matches[1]&cat_name[]=$matches[2]&cat_name[]=$matches[3]&cat_name[]=$matches[4]\',
\'top\' );
add_rewrite_rule( \'^cities/(.*)/browse/(.*)/(.*)\',
\'index.php?city_name=$matches[1]&cat_name[]=$matches[2]&cat_name[]=$matches[3]\',
\'top\' );
add_rewrite_rule( \'^cities/(.*)/browse/(.*)\',
\'index.php?city_name=$matches[1]&cat_name[]=$matches[2]\',
\'top\' );
add_rewrite_rule( \'^cities/?([^/]*)/browse\',
\'index.php?city_name=$matches[1]\',
\'top\' );
flush_rewrite_rules(true);
}, 10, 0);
如何重写
(.*)/(.*)/(.*)/(.*)
并获得
$matches
作为阵列?的第一个元素
$matches
是city\\u name变量值,其余是cat\\u name数组元素。
现在一切都正常了,但我知道代码可以小得多。
SO网友:mmm
所有部件可选?
, 您可以获得一条规则来管理所有规则:
add_rewrite_rule(
\'^cities/(.*)/(browse)?/?(.*)?/?(.*)?/?(.*)?/?(.*)?/?\',
\'index.php?city_name=$matches[1]&cat_name[]=$matches[3]&cat_name[]=$matches[4]&cat_name[]=$matches[5]\',
\'top\'
);
但是
[]
无法使用WordPress逻辑,则需要使用数字定义重写标记。试试看:
add_rewrite_tag("%cat_name.%", "([^&]+)");
add_rewrite_rule(
\'^cities/([^/]*)/(browse)?/?([^/]*)?/?(^/)?/?([^/]*)?/?([^/]*)?/?\',
\'index.php?city_name=$matches[1]&cat_name1=$matches[3]&cat_name2=$matches[4]&cat_name3=$matches[5]\',
\'top\'
);