带有可选参数的添加_重写_规则

时间:2021-09-25 作者:Mads

使用add\\u rewrite\\u rule()为自定义帖子类型;目录;,“页码名称”;汽车:

/目录/汽车//目录/汽车/p1//目录/汽车/p1/p2//目录/汽车/p1/p2//目录/汽车/p1/p2/p3/

在/cars/之后,我的参数从未超过3个,但所有参数都具有可选的查询字符串参数。像这样:

/目录/汽车/p1/p2/?最大重量=3200

这是我的代码:

add_rewrite_rule( 
    \'^catalogs/([^/]*)/([^/]*)/([^/]*)/([^/]*)/?\', 
    \'index.php?catalogs=$matches[1]&p1=$matches[2]&p2=$matches[3]&p3=$matches[4]\', 
    \'top\'
);
当有3个参数(如/catalogs/cars/p1/p2/p3/)时效果很好,但当有0-2个参数时效果不好。

我试过让部分regex成为可选的,但我想我的regex技能并没有那么好。。。

有没有一个技巧可以让参数的数量动态变化,这样从0到3个参数都可以处理?

谢谢:拇指支持:

1 个回复
SO网友:Mads

找到了解决方案,只需记住所有的?标记。

当正则表达式如下所示时,它会起作用:

\'index.php?catalogs=$matches[1]&p1=$matches[2]&p2=$matches[3]&p3=$matches[4]\'

相关推荐

Ajax WordPress pass post URLs

我正在使用wp_localize_script 将post数据发送到ajax。wp_localize_script( \'my-script.js\', \'ajax_object\', array(\'ajax_url\' => admin_url(\'admin-ajax.php\')) ); add_action( \'wp_ajax_load_more_posts\', \'ajax_posts\' ); 将post数据发送到ajax:function ajax_posts