Having a problem with rewrite_rules and rewrite_tags – url not rewriting properly and query var missing

Question

I am almost tearing my hair out trying to get to grips with the WordPress rewrite rules and tags.

From within a plugin, I’ve created a page called ‘childpage’, it is the child of another page called ‘parentpage’. On this page, a query var ‘lbc’ is passed and is always a 6 char hex value, like a color value used in html/css.

So this url works fine:

example.com/parentpage/childpage/?lbc=a1b2c3

There is also another page called ‘otherpage’, which also takes a query var (called ‘rjd’) which is also always a 6 char hex value – so this url works fine:

example.com/otherpage/?rjd=d4e5f6

What I want is for rewrite rules to make the following possible: example.com/c/a1b2c3 and example.com/c/a1b2c3/any-old-blah-blah to show the same content as example.com/parentpage/childpage/?lbc=a1b2c3 but without changing the url in the browser address bar.

Also for: example.com/r/d4e5f6 and example.com/r/d4e5f6/any-old-blah-blah to show the same content as example.com/otherpage/?rjd=d4e5f6 but without changing the url in the browser address bar.

To achieve this I have added some rewrite rules and tags as follows:

function add_rewrites(){
    add_rewrite_tag(
        '%rjd%',
        '(.{6})'
    );

    add_rewrite_rule(
        '^r/(.{6}).*?$',
        'index.php?pagename=otherpage&rjd=$matches[1]',
        'top'
    );

    add_rewrite_tag(
        '%lbc%',
        '(.{6})'
    );

    add_rewrite_rule(
        '^c/(.{6}).*?$',
        'index.php?pagename=childpage&lbc=$matches[1]',
        'top'
    );

}
add_action( 'init', 'add_rewrites' );

And have flushed the rewrite rules by clicking save on the setting/permalinks admin page.

The result being that one works fine but the other doesn’t. Now both example.com/r/d4e5f6 and example.com/r/d4e5f6/any-old-blah-blah show the same content as example.com/otherpage/?rjd=a1b2c3 and without changing the url in the browser address bar.

But example.com/c/a1b2c3 and example.com/c/a1b2c3/any-old-blah-blah change the url in the browser address bar to example.com/parentpage/childpage and no query var is available to the plugged in shortcode on the page, so the content does not match example.com/parentpage/childpage/?lbc=a1b2c3

I have been searching all over for an answer but the documentation for add rewrite stuff in WordPress isn’t helping, nor can I work out from other people’s questions, etc.

Can anyone please point out where I am going wrong and/or point me in the direction of any actual detailed, worthwhile descriptions/tutorials on just how the WordPress rewrite rules and tags work?

0
appshine 4 months 2020-12-29T02:10:19-05:00 0 Answers 2 views 0

Leave an answer

Browse
Browse