0

I have a Custom Post Type named "Cars" and 2 Custom Taxonomies "Ferrari" and "Lamborghini". Each taxonomy has 2 Terms: "New" and "Used".

These URIs work as expected:

http://myhost/ferrari/new
http://myhost/ferrari/used

The problem is, of course, when I append the car ID at the end I get a 404:

http://myhost/ferrari/new/123

I've been playing a lot with add_rewrite_rule/add_rewrite_tag and read many discussions here on StackExchange but I couldn't find a solution. I also tried WP Router and it actually works, but it almost entirely overrides the default routing so that it feels like a hack.

Question:

All I need is being able to route the URI with the appended ID to the same template as it would without, so from there I can make a custom query using the ID segment.

Thank you!

1

1 Answer 1

0

You can try this:

function my_car_rewrite_rules( $rules ) {
    $newrules = array();

    // add a rule for this kind of url:
    // http://myhost.com/cars/ferrari/used/123
    // => http://myhost.com/index.php?post_type=cars&ferrari=used&p=123 

    $newrules['^cars/([^/]+)/([^/]+)/([^/]+)$'] = 'index.php?post_type=cars&$matches[1]=$matches[2]&p=$matches[3]';
    return $newrules + $rules;
}
add_filter('rewrite_rules_array','my_car_rewrite_rules');

and remember to "save the permalinks" when testing.

I added /cars/ so this rewrite will not overwrite your other pages.

You can also try this more restrict rule:

$newrules['^cars/([a-z]+)/([a-z]+)/([0-9]+)$'] = 'index.php?post_type=cars&$matches[1]=$matches[2]&p=$matches[3]';

or even

$newrules['^cars/([ferrari|lamborghini]+)/([used|new]+)/([0-9]+)$'] = 'index.php?post_type=cars&$matches[1]=$matches[2]&p=$matches[3]';

To remove the CPT from URI (need to do it for each taxonomy)

$newrules['^ferrari/([^/]+)/([^/]+)$'] = 'index.php?post_type=cars&$ferrari=$matches[1]&p=$matches[2]';
2
  • Brilliant! I've also added a modified rule to allow taxonomy/term/id, instead of cpt/taxonomy/term/id. Thank you very much.
    – gyo
    Feb 8, 2013 at 10:16
  • ok great ;-) (I approved your edit so it should show up now)
    – birgire
    Feb 8, 2013 at 10:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.