Rewrite WordPress Custom URL

时间:2018-08-17 作者:Sonjoy Datta

我有一个自定义的WordPress url,它是由ID. 我必须重写此urlhttps://example.com/account/customer-bookings/?view-booking=4https://example.com/account/customer-bookings/view-booking/4. 我怎么做?

我的当前。htaccess代码如下所示,

# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

# END WordPress

# php -- BEGIN cPanel-generated handler, do not edit
# Set the “ea-php56” package as the default “PHP” programming language.
<IfModule mime_module>
  AddType application/x-httpd-ea-php56 .php .php5 .phtml
</IfModule>
# php -- END cPanel-generated handler, do not edit

1 个回复
最合适的回答,由SO网友:kero 整理而成

WordPress有自己的系统来管理重定向和页面路由,您无需编辑。htaccess文件。您需要从函数开始add_rewrite_rule().

它需要3个参数:

路由(作为regex)查询变量account/customer-bookings/. 如果它是一个页面,它可以是page_id. 要复制WordPress已经完成的功能,可以是(XXX是特定的page\\u id):

add_rewrite_rule(
    \'^account/customer-bookings/?$\',
    \'index.php?page_id=XXX\'
);
现在,您只需扩展以下内容:(don\'t forget to flush rewrite rules after adding this code!)

add_action(\'init\', \'wpse_view_booking_rewrite\');
function wpse_view_booking_rewrite() {
    add_rewrite_rule(
        \'^account/customer-bookings/view-booking/([^/]+)/?$\',
        \'index.php?page_id=XXX&view-booking=$matches[1]\',
        \'top\'
    );
}
这应该已经显示了正确的页面。但是,您将无法使用get_query_var(\'view-booking\'), 因为它不是默认变量。要解决这个问题,只需告诉WP像这样小心

add_filter(\'query_vars\', \'wpse_view_bookings_filter\');
function wpse_view_bookings_filter($vars) {
    $vars[] = \'view-booking\';
    return $vars;
}
此时WordPress知道变量,并通过调用get_query_var(\'view-booking\') 您将获得适当的变量。

结束