2012-10-24 115 views
1

所以我有一个WordPress的页面在这里:WordPress URL地址重写

http://12.ourgreenville.com/real_estate/

我希望能够把在URL中两个可变(城市/州),然后与他们合作 。一个URL应该是这样的:

http://12.ourgreenville.com/real_estate/1/2/

请让我知道需要什么。我把你的代码的functions.php为 如下:

function add_rewrite_rules($wp_rewrite) 
{ 
    $new_rules = array(
        '('.$template_page_name.')/real_estate/(.*?)/?([0-9]{1,})/?$' =>'index.php?p=5351city='.$wp_rewrite->preg_index(1).'&state='.$wp_rewrite->preg_index(2) 
       ); 

$wp_rewrite->rules = $new_rules + $wp_rewrite->rules; 
} 
add_action('generate_rewrite_rules', 'add_rewrite_rules'); 

function query_vars($public_query_vars) { 

    $public_query_vars[] = "city"; 
    $public_query_vars[] = "state"; 
    return $public_query_vars; 
} 
add_filter('query_vars', 'query_vars'); 

我不知道我在做什么wrong.kindly帮我做。

回答

1

您错过了一个非常重要的步骤 - 刷新规则以激活对它们的更改。这是我的工作变型与适应你的情况:

add_action('init', 'prefix_attach_page_rules'); 
add_filter('query_vars', 'prefix_attach_page_query_vars'); 
add_action('parse_request', 'prefix_attach_page_request'); 

function prefix_attach_page_rules() 
{ 
    add_rewrite_rule('^' . urlencode(get_option('non_latin_data')) . '/(\d+)/(\d+)/?$', 'index.php?prefix_view=my_special_id&prefix_city_=$matches[1]&prefix_state=$matches[2]', 'top'); 


    flush_rewrite_rules(); // IMPORTANT 
} 

function prefix_attach_page_query_vars($query_vars) 
{ 
    $query_vars[] = 'prefix_city'; 
    $query_vars[] = 'prefix_state'; 
    return $query_vars; 
} 

function prefix_attach_page_request(&$wp) 
{ 
    // If the page request is really from our rewrite url 
    if(!array_key_exists('prefix_view', $wp->query_vars)) 
     return; 

    $city= $wp->query_vars['prefix_city']; 
    $state = $wp->query_vars['prefix_state']; 

    // we are on the rewrite rule 
    exit; // in case very custom page like include 
} 

前缀,在程序执行的情况下,你是非常重要的。你可以放置任何你喜欢的东西,但它可以让你逃避重复常见名字的情况。

使用选择的动作或过滤器您不应该使用您的动作或过滤器,但重要的是使您的规则具有更高的优先级(顶部)并刷新规则。

prefix_attach_page_rules会告诉WordPress的为我们的规则

prefix_attach_page_request时parsing_request在这种情况下,由给定的查询瓦尔会做我们的工作。

还有另一个StackOverflow:WordPress Answers - 专注于WordPress,你也可以在那里找到许多解决方案。

附加(基于注释链路上的正则表达式):

add_rewrite_rule('^real_estate/(\d+)/(\d+)/?$', 'index.php?prefix_view=real_estate&real_estate_city_id=$matches[1]&real_estate_state_id=$matches[2]', 'top'); 

那么你应该寻找他们real_estate_city_idreal_estate_state_id查询瓦尔和page_request ...

+0

感谢Rolice,但问题是,我完全遵循你的代码,但仍然得到404错误。当我打http://12.ourgreenville.com/real_estate/1/2/。请帮助我。 –

+0

@JahanZaibAslam,你可以进行一些调试,在cetain点处回显或死掉php,例如,三个函数中每一个都有什么:'prefix_attach_page_query_vars' - 示例die(print_r($ wp)),'prefix_attach_page_request' - 例如die(print_r($ wp))。这是非常可能的,然后正则表达式对于想要的情况无效 - 请参阅上面的帖子的编辑添加。你是否启用了固定链接? – Rolice