0

I'm currently developing a WordPress site that has an unusual taxonomy. In order to get around certain issues I need to add a parameter to the end of the URL. I have this working, however I need some way of using mod_rewrite to make the parameter pretty.

Here is what I currently have...

www.site.com/('director-name' or 'project-name')/?path=('visual' or 'production')

for example: www.site.com/joe-smith/?path=visual

I am using the $_GET to access this variable for my functionality, and it works fine. The issue is I want to make the URL read...

www.site.com/joe-smith/visual OR www.site.com/art/production

I have read that messing with the .htaccess in WordPress isn't the best way to deal with this.

Help will be much appreciated. Thanks!

4

1 回答 1

1

由于您使用的是 Wordpress,因此您无需对 .htaccess 或 mod_rewrite 执行任何操作。Wordpress 有一个用于处理重写规则的内置系统。您还可以直接在函数中设置 URL 参数。该功能是add_rewrite_rule()和codex中的示例非常好。不过,我可以引导你完成它,这样你就可以确切地看到发生了什么。

从示例中获取以下重写规则:

add_rewrite_rule('^nutrition/([^/]*)/([^/]*)/?','index.php?page_id=12&food=$matches[1]&variety=$matches[2]','top');

首先,让我们回顾一下函数参数。第一个参数是重写的正则表达式。如果此正则表达式在当前 URL 上找到匹配项,您的重写将开始。任何 URL 参数都将加载到一个$matches数组中,以便稍后在函数的第二个参数中使用。

第二个参数是将被重写的实际 URL。请注意,此处使用的是 page_id,而不是 page slug。重要的是,您为此参数使用页面 ID 而不是 slug,因为 slug 本身就是重写。后面的参数是您传递给处理程序的查询字符串的值。

您可能知道,Wordpress 中的所有页面都通过 index.php 文件进行路由。如果你熟悉 MVC,这很像前端控制器。因此,您的所有重写都应在开头包含 index.php 文件。这反映在此函数的第二个参数中。您可以使用其他文件进行自定义重写,但为了简单起见,我们假设您使用的是标准的 Wordpress index.php 文件。

最后一个参数是队列中应该放置重写的位置。您可以使用“顶部”或“底部”。在 Wordpress 重写之前加载顶部,之后加载底部。

使用此功能,Wordpress 将即时向您的 htaccess 添加行并根据当前页面更新它们。这绝对是在 Wordpress 中进行重写的最佳方式!希望这可以帮助!

根据评论更新

您可以将此代码放在您的functions.php 文件中。您应该将其包装在一个函数中,并将其挂钩到在重写规则之前触发的操作。这是一个与您的确切问题相匹配的示例:

add_action('init', 'my_custom_rewrite_function');
function my_custom_rewrite_function() {
    $director_category_id = 5; // Change to correct id
    $project_category_id = 6; // Change to correct id
    $handler_page_id = 25 // The page ID for the handler

    add_rewrite_rule('^director/([^/]*)/([^/]*)/?','index.php?page_id=$handler_page_id&category=$director_category_id&name=$matches[1]&path=$matches[2]','top');
    add_rewrite_rule('^project/([^/]*)/([^/]*)/?','index.php?page_id=$handler_page_id&category=$project_category_id&name=$matches[1]&path=$matches[2]','top');

    flush_rewrite_rules(); // This will make sure that the rewrite rules are added
}

然后,您可以通过get_query_var()对每个查询字符串参数执行 a 来处理自定义模板中的查询。

于 2013-09-10T21:22:57.777 回答