I have a custom WordPress url which is generated by ID. I have to rewrite this url https://example.com/account/customer-bookings/?view-booking=4
to https://example.com/account/customer-bookings/view-booking/4
. How Can I don it?
My Current .htaccess code is following,
# 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
WordPress has its own system managing redirects and page routes, you don’t need to edit the .htaccess file. You’ll want to start with the function add_rewrite_rule()
.
It takes 3 arguments:
- route (as regex)
- query vars
- priority
So first, you need to find out the query vars of account/customer-bookings/
. If it is a page, it can be page_id
. To reproduce what WordPress already does, it could be (XXX being the specific page_id):
add_rewrite_rule(
'^account/customer-bookings/?$',
'index.php?page_id=XXX'
);
Now you just need to expand this: (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'
);
}
This should already present the correct page. However, you won’t be able to use get_query_var('view-booking')
, because it is no default variable. To solve this, simply tell WP to watch out for it like so
add_filter('query_vars', 'wpse_view_bookings_filter');
function wpse_view_bookings_filter($vars) {
$vars[] = 'view-booking';
return $vars;
}
At this point WordPress knows about the variable, and by calling get_query_var('view-booking')
you will get the proper variable.