WordPress URL rewriting – part of URL after an existing page

I’m trying to rewrite the following URLs like so (%2F is /):

/archives/JHW
 -> /archives?RefNo=JHW

/archives/JHW/1/1
 -> /archives?RefNo=JHW%2F1%2F1

/archives
 -> no redirect

The idea is to get the URLs looking nice, but then be able to grab the rest of the path with just $_GET['RefNo'] from the /archives page, which already exists as a page. So far I’ve got:

Read More
RewriteRule ^archives/(.+)/? /index.php/archives/?RefNo=$1 [QSA,L]

But this doesn’t seem to be working at all.

I’ve been adding it with this code inside my functions.php for my theme:

add_rewrite_rule(
    'archives/(.+)/?',
    'index.php/archives?RefNo=$1',
    'top'
);

and then gone to the Permalinks page in /wp-admin to make it regenerate the .htaccess file. When I look at the .htaccess the rule is in there, it just isn’t kicking in like I’m expecting.

Where am I going wrong?


Update

My current .htaccess file is:

<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteRule ^archives/(.+)/? /index.php/archives/?RefNo=$1 [QSA,L]
    RewriteRule ^index.php$ - [L]
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule . /index.php [L]
</IfModule>

Related posts

Leave a Reply

1 comment

  1. One possible solution which I’ve stumbled across is this (inside the theme’s functions.php):

    function archives_page_rewrites() {
        add_rewrite_tag('%RefNo%', '([^&]+)');
        add_rewrite_rule(
            '^archives/(.*)/?$',
            'index.php?pagename=archives&RefNo=$matches[1]',
            'top'
        );
    }
    add_action('init', 'archives_page_rewrites');
    

    I’m willing to believe there are other ways of doing it, and that this may or may not be the best solution. Feel free to up/down this based on if it’s good/bad in terms of good-practice.