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

1 Answer
1

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:

  1. route (as regex)
  2. query vars
  3. 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.

Leave a Reply

Your email address will not be published. Required fields are marked *