2012-04-27 65 views
1

我试图重写以下URL在WP: http://www.example.com/?compra=arriendo&propertytype=apartamentos&location=bogota&habitaciones=2-habitacionesWordPress的URL重写 - 可选值

到: http://www.viveya.co/arriendo/apartamentos/bogota/2-habitaciones

这是我的代码:

功能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');

现在,我想向城市显示是可选的。所以,如果我输入以下URL: http://www.viveya.co/arriendo/apartamentos/bogota/

它仍然会工作。 (原始URL将为& habitaciones =)。当城市显示为空

我的代码不能正常工作。我不知道为什么。我的正则表达式有什么问题?

在此先感谢! 亚当

+0

为什么您没有在[WPSE](http://wordpress.stackexchange.com/)上发布此信息的具体原因? – scribu 2012-05-03 10:56:49

回答

1

这是不是可以用正则表达式来解决。

你需要使用PHP解析URL段。

$segments = explode('/', $url); 

$query = array(); 

while ($segments) { 
    $part = array_shift($segments); 

    if (in_array($part, array('taxonomy1', 'taxonomy2', ...)) { 
    $query[ $part ] = array_shift($segments); 
    } 
} 

编辑:概念的未经检验的证明好吧,我想你也可以使用正则表达式,但你需要为每一个可选值的附加重写规则:

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'); 

来源:http://thereforei.am/2011/10/28/advanced-taxonomy-queries-with-pretty-urls/

+0

非常感谢,为每个可选值添加了额外的重写规则!! :) – AdamGold 2012-05-04 12:26:49