Reputation: 5051
I am trying to rewrite the following URL in WP: http://www.example.com/?compra=arriendo&propertytype=apartamentos&location=bogota&habitaciones=2-habitaciones
to: http://www.viveya.co/arriendo/apartamentos/bogota/2-habitaciones
This is my code:
function eg_add_rewrite_rules() { global $wp_rewrite;
$new_rules = array( '(.+)/(.+)/(.+)/(.*)/?$' => 'index.php?compra=' . $wp_rewrite->preg_index(1) . '&propertytype=' .
$wp_rewrite->preg_index(2) . '&location=' . $wp_rewrite->preg_index(3) . '&habitaciones=' . $wp_rewrite->preg_index(4) ); $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
add_action( 'generate_rewrite_rules', 'eg_add_rewrite_rules' );
Now, I want habitaciones to be optional. So if I enter the following URL: http://www.viveya.co/arriendo/apartamentos/bogota/
It will still work. (the original URL will be &habitaciones=).
My code doesn't work when habitaciones is empty. I have no idea why. What's wrong with my regex?
Thanks in advance! Adam
Upvotes: 1
Views: 594
Reputation: 3078
This is not something that can be solved with regular expressions.
You need to parse the URL segments using PHP. Untested proof of concept:
$segments = explode( '/', $url );
$query = array();
while ( $segments ) {
$part = array_shift( $segments );
if ( in_array( $part, array( 'taxonomy1', 'taxonomy2', ... ) ) {
$query[ $part ] = array_shift( $segments );
}
}
Edit: Well, I suppose you could also use regex, but you'll need an additional rewrite rule for each optional value:
function eg_add_rewrite_rules() {
global $wp_rewrite;
$new_rules = array(
'event/(industry|location)/(.+)/(industry|location)/(.+)/?$' => 'index.php?post_type=eg_event&' . $wp_rewrite->preg_index(1) . '=' . $wp_rewrite->preg_index(2) . '&' . $wp_rewrite->preg_index(3) . '=' . $wp_rewrite->preg_index(4),
'event/(industry|location)/(.+)/?$' => 'index.php?post_type=eg_event&' . $wp_rewrite->preg_index(1) . '=' . $wp_rewrite->preg_index(2)
);
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}
add_action( 'generate_rewrite_rules', 'eg_add_rewrite_rules' );
Source: http://thereforei.am/2011/10/28/advanced-taxonomy-queries-with-pretty-urls/
Upvotes: 1