dongya9904
dongya9904
2018-10-18 19:37

在wordpress中重写URL 2次

I have a functionality on first page it lists all states on click of any states in next page it lists cities related to that state and on click f city it shows city page. State list page - https://benefitsexplorer.com/get-help/unclaimed-money/

originally url for city listing page was https://benefitsexplorer.com/cities/?lp=unclaimed-money&state=North%20Carolina/

I have added url rewrites successfully for this page using this code

function rewrite_state_url(){
    add_rewrite_rule('^get-help/([^/]*)/([^/]*)/?','index.php?
    page_id=2931&lp=$matches[1]&state=$matches[2]','top');
}
function register_custom_query_vars($vars){
    array_push($vars, 'lp');
    array_push($vars, 'state');
    return $vars;
}
add_action('init','rewrite_state_url',1);
add_filter('query_vars', 'register_custom_query_vars',1);

So its showing url like i wanted https://benefitsexplorer.com/get-help/unclaimed-money/North%20Carolina

But i am trying now same for city page which will take parameter lastpage, state and city.

so i have added code like

function rewrite_city_url(){
    add_rewrite_rule('^get-help/([^/]*)/([^/]*)/([^/]*)/?','index.php?page_id=2944&lp=$matches[1]&state=$matches[2]&city=$matches[3]','top');
}
function register_custom_query_vars1($vars){
    array_push($vars, 'lp');
    array_push($vars, 'state');
    array_push($vars, 'city');
    return $vars;
}
add_action('init','rewrite_city_url',2);
add_filter('query_vars', 'register_custom_query_vars1',2);

now its showing url https://benefitsexplorer.com/get-help/unclaimed-money/North%20Carolina/Locust/

but its showing same page which is showing at state list url https://benefitsexplorer.com/cities/?lp=unclaimed-money$state=North%20Carolina/

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • doujiu3882 doujiu3882 3年前

    Try combine:

     function rewrite_state_url(){
         add_rewrite_rule('^get-help/([^/]*)/([^/]*)/([^/]*)/?','index.php?page_id=2944&lp=$matches[1]&state=$matches[2]&city=$matches[3]','top');
         add_rewrite_rule('^get-help/([^/]*)/([^/]*)/?','index.php?page_id=2931&lp=$matches[1]&state=$matches[2]','top');
     }
     function register_custom_query_vars($vars){
        array_push($vars, 'lp');
        array_push($vars, 'state');
        array_push($vars, 'city');
        return $vars;
     }
     add_action('init','rewrite_state_url',1);
     add_filter('query_vars', 'register_custom_query_vars',1);
    

    Also flush your permalinks (admin > settings > permalinks and hit save without changing anything)

    The order in the add_rewrite_rule is important, so do not change it! And perhaps change your function name because now it contains state AND city :)

    点赞 评论 复制链接分享

为你推荐