Passing variables through permalink structure

I have a WordPress page which is accessible via /accommodation/.

What I want to be able to do is pass in a parameter using the URL – ie going to /accommodation/value1/ would load the same page as /accommodation/ – but still show the /accommodation/value1/ in the browser address bar.

Read More

I guess another way of putting it would be to say I need to be able to access /accommodation/ by adding anything I like to the end of the URL, whilst retaining the URL I entered in the browser window.

I’ve then got some code in the page template which does different things based on the values passed into the page.

Whilst I could use a query string, I want to avoid doing that so I can keep the “pretty URLs”.

Many thanks for any help / suggestions.

Related posts

Leave a Reply

1 comment

  1. Solved it!

    // Register the variables that will be used as parameters on the url
    function add_my_var($public_query_vars) {
        $public_query_vars[] = 'extra_slug';
        return $public_query_vars;
    }
    add_filter('query_vars', 'add_my_var');
    
    // Build the rewrite rules, for the extra parameter
    function do_rewrite() {
        add_rewrite_rule('(accommodation)/[/]?([^/]*)$', 'index.php?pagename=accommodation&extra_slug=$matches[2]','top');
    }
    add_action('init', 'do_rewrite');
    
    // The parameter is now accessible
    get_query_var('extra_slug')