【问题标题】:Wordpress add_rewrite_rule: custom post type links with subdomainWordpress add_rewrite_rule:带有子域的自定义帖子类型链接
【发布时间】:2016-07-13 02:58:42
【问题描述】:

我创建了一个自定义帖子类型,对于这个自定义帖子类型,我有这样的单一页面 http://example.com/?custom_post=titlehere

我怎样才能将此网址(使用 add_rewrite_rule )重写为类似的链接

http://titlehere.example.com

到目前为止我有这个代码

function custom_rewrite_basic() {
  add_rewrite_rule('^http://[\w.-]+\.example.com?', 'custom_post=$matches[1]', 'top');
}
add_action('init', 'custom_rewrite_basic');

我是不是写错了正则表达式?

【问题讨论】:

    标签: regex wordpress mod-rewrite url-rewriting


    【解决方案1】:

    是的,如果您查看This Demo,您会看到// 带有下划线。这是因为他们没有逃脱。应该像这样选择它们,\/\/。

    这是您应该使用的正则表达式:

    ^http:\/\/[\w.-]+\.example.com?
    

    Live Demo on RegExr

    另外,我不确定你是否想选择?,因为目前它使com 中的m 成为可选的,但如果你这样做了,你需要像这样转义它,\?。但是,这将选择http://foo.example.com?something,如果要选择http://foo.example.com/?something,请使用以下RegEx:

    ^http:\/\/[\w.-]+\.example.com\/\?
    

    请注意,使用我上面指定的任何 RegEx 可能仍然无法正常工作。 $matches[1] 选择 RegEx 中的第一个匹配项,但是您没有捕获组。我建议使用以下完整代码:

    function custom_rewrite_basic() {
      add_rewrite_rule('^http:\/\/([\w.-]+)\.example.com\/?', 'custom_post=$matches[1]', 'top');
    }
    add_action('init', 'custom_rewrite_basic');
    

    【讨论】:

    • 感谢您的回答,但仍然无法正常工作:代码为 add_rewrite_rule('^http:\/\/[\w.-]+\.example.com?/g', 'custom_post =$matches[1]', 'top');
    • @user1548981 查看我的编辑,您忘记包含捕获组,所以$matches[1] 不存在!
    • 再次感谢。仍然无法正常工作,但我不认为这一次应该归咎于正则表达式。我在这里看到regexr.com/3d3an 找到了匹配项。代码为 add_rewrite_rule('^http:\/\/([\w.-]+)\.example.com\/?', 'custom_post=$matches[1]', 'top');
    • @user1548981 试试$matches[0] 看看...?还有,这是怎么回事,是不是重定向,重定向到错误的地方,抛出错误?
    • 尝试了 $matches[0] 和 $matches[2] - 仍然无法正常工作
    猜你喜欢
    • 1970-01-01
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 2012-01-01
    • 2014-05-17
    • 1970-01-01
    • 1970-01-01
    • 2021-06-17
    相关资源
    最近更新 更多