Custom post type with add_rewrite_rule

I’m using a custom post type (cases). So when I’m going to domain.com/cases I see a overview of all cases. I’m using a custom taxonomy to categorize these cases. In 2 levels. So first an industry:

domain.com/cases/lifesciences > shows all cases within this industry

Read More

And a second level

domain.com/cases/lifesciences/strategy > shows all cases within industry & category.

I’ve all taken care of this by using add_rewrite_rule script in my functions.php:

add_rewrite_rule(
    '^cases(/([^/]+))?(/([^/]+))?/?',
    'index.php?page_id=4&industry=$matches[2]&subcat=$matches[4]',
    'top'
);

the only downside of this is that I cannot go to the single-cases.php page when I go to:

domain.com/cases/lifesciences/strategy/this-is-a-post
This is just showing the same page as If you go to /cases

It is possible when I change ‘top’ into ‘bottom’ of the add_rewrite_rule. But then I cannot go to domain.com/cases/lifesciences because it will forward to domain.com/lifesciences. Because this is also a contentpage.

I think I need to change the regular expression to ignore the rule when there is a third ‘directory’ and then just let wordpress do the work. Because the permalink of the actual case is correct because I used
add_filter(‘post_type_link’, ‘industry_permalink’, 10, 3); for that.

Related posts

1 comment

  1. The solution is to make the rex exp more strict and a $ sign to ignore further parameters.

    add_rewrite_rule(
        '^cases(/([^/]+))?(/([^/]+))?/?$',
        'index.php?page_id=4&industry=$matches[2]&subcat=$matches[4]',
        'top'
    );
    

Comments are closed.