Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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!

share|improve this question
    
Try to follow this question and it's solution: wordpress.stackexchange.com/questions/39500/… –  david.binda Feb 7 '13 at 10:45
add comment

1 Answer 1

up vote 0 down vote accepted

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]';
share|improve this answer
    
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 '13 at 10:16
    
ok great ;-) (I approved your edit so it should show up now) –  birgire Feb 8 '13 at 10:29
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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