I have a custom post type residential using a custom taxonomy residential_taxonomies and I am adding the taxonomy term(s) and the post type name to the url.

It works fine if there are always a parent & child taxonomy term making the url like /residential/tax-1/tax-2/post-slug, but I don't know how to update my matching RegExp to match either 1 or 2 taxonomy terms and be either /residential/tax-1/tax-2/post-slug or /residential/tax-1/post-slug if only one taxonomy is selected.

I know how to do either or but not both.

My current code is as follows:

add_filter('rewrite_rules_array', 'mmp_rewrite_rules');

function mmp_rewrite_rules($rules) {
    $newRules  = array();

    $newRules['residential/(.+)/(.+)/(.+)/?$'] = 'index.php?residential=$matches[3]';
    $newRules['residential/(.+)/(.+)/?$'] = 'index.php?residential_taxonomies=$matches[2]';

    return array_merge($newRules, $rules);
  • 1
    If something might be either a tax term or a post slug, there's no way to resolve that with just regex, you have to do something like this to resolve the ambiguity. – Milo Aug 20 '18 at 23:00
  • That solution worked perfectly. I don't quite understand it at this point. Will need to dig into more. Thank you – Nate Beers Aug 21 '18 at 0:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.