Search code examples
wordpressurl-rewritingurl-routing

Incorrect routing with wordpress rewrite


I have a page setup with the permalink of mydomain.com/events which uses a page template. This page show all my events pulled in from an external source (so can't be a custom post type). I've then setup rewrites to handle a categories parameter to the url and then single events.

add_action('init', 'mydomain_events_rewrite');
function mydomain_events_rewrite()
{
    add_rewrite_rule(
        '^events/categories/?$',
        'index.php?category=$matches[1]',
        'top'
    );

    add_rewrite_rule(
        '^events/?$',
        'index.php?event=$matches[1]',
        'top'
    );
}

add_filter('query_vars', 'mydomain_events_rewrite_var');
function mydomain_events_rewrite_var($vars)
{
    $vars[] = 'events';
    $vars[] = 'categories';
    return $vars;
} 

So the idea is categories would just provide the category variable to the events page, for example mydomain.com/events/categories/film. And then individual events would be mydomain.com/events/123/my-epic-film.

As it stands, if I go to mydomain.com/events it just redirects me to the homepage. But if I use the rewrite urls, mydomain.com/events/categories/film it goes to a 404. Where am I going wrong here?

Thanks!


Solution

  • So I was missing the correct regex and the page

    add_rewrite_rule(
        '^events/category/([^/]*)/?',
        'index.php?pagename=events&category=$matches[1]',
        'top'
    );
    
    add_rewrite_rule(
        '^events/([^/]*)?',
        'index.php?pagename=events&event=$matches[1]',
        'top'
    );