2016-08-19 117 views
-1

我在尝试学习如何将此URL写入正则表达式模板以添加为重写时遇到问题。我已经试过各种正则表达式沙箱的数字出来我自己,但他们不会允许一个“/”例如,当我从这里复制的表达式来进行测试:demoURL重写正则表达式转换

我有一个自定义后类型(出版物)与2分类学(杂志,问题),我试图创造一个漂亮的网址。

很多小时后,我来到这里,了解如何将其转换。

index.php?post_type=publications&magazine=test-mag&issue=2016-aug 

向模板的正则表达式的表达式(出版物杂志问题是常数),可以输出。

http://example.com/publications/test-mag/2016-aug/ 

希望有空间可以扩展,如果从该页面跟随一篇文章。

在此先感谢。

编辑1:

我得为我的规则:

^publications/([^/]*)/([^/]*)/?$ 

,这对我的比赛:

^index.php?post_type=publications&magazine=$matches[1]&issue=$matches[2]$ 

和测试这一点:

http://localhost/publications/test-mag/2016-aug/ 

,但它给了我一个404.什么问题?

+0

您将使用哪个URL重写引擎? – 10100111001

+0

@ 10100111001 Wordpress rewrite – 4t0m1c

回答

1

^index\.php\?post_type=publications&magazine=([^&]+)&issue=([^&]+)$

  • ^开始
  • index\.php\?post_type=publications&magazine=文字文本
  • ([^&]+)一个或多个非符号字符(将得到所有文字到下一个URL参数,这是捕获为一组
  • &issue=字面文字
  • ([^&]+)一个或多个non-ampers和字符。串
+0

非常感谢,并且这些**([^&] +)**也可以作为比赛的一种变量吗? – 4t0m1c

+0

他们没有。他们只是为了让你在代码中分别获得这些字符串。 – Whothehellisthat

+0

如何在重写中回调这些字符串?对不起,我是完全新的正则表达式 – 4t0m1c

1
$str = 'index.php?post_type=publications&magazine=test-mag&issue=2016-aug'; 
preg_match('/magazine=([\w-]+?)&issue=([\w-]+)/', $str, $matches); 
$res = 'http://example.com/' . $matches[1] . '/' . $matches[2] . '/'; 
echo $res; // => http://example.com/test-mag/2016-aug/ 
1

也捕获

  • $端可以使用WP重写API在add_rewrite_rule的方法来做到这一点。

    add_rewrite_rule('^/([^/]*)/([^/]*)/?$','index.php?post_type=publications&magazine=$matches[1]&issue=$matches[2]','top');