I want to be able to change the value of a wordpress page url according to a selected value from a dropdown list via a custom post type.
I want to use several dropdowns such that "Country" then "State" then "City" then "Town" will change the url to the selected values.
If i select just the country then the url will look like
http://example.com/india
When i select states of india in addition to that then the url will look like http://example.com/india/delhi
.
Please reference this page to see an example of what I am trying to do: http://areapincode.in/
You should search for URL rewrite in WordPress. Please see the following link for more detail,
It works like following,
Add action hook for rewrite,
add_action( 'init', 'rewrites_init', 1, 0);
function rewrites_init() {
add_rewrite_rule('([^/])/([^/])/([^/])/([^/])', 'index.php?&country=$matches1&state=$matches2&city=$matches[3]&town=$matches[4]', 'top');
}
Set rewrite tags
add_action( 'init', 'custom_rewrite_tag', 10, 0); function custom_rewrite_tag() { add_rewrite_tag('%country%', '([^&]+)'); add_rewrite_tag('%state%', '([^&]+)'); add_rewrite_tag('%city%', '([^&]+)'); add_rewrite_tag('%town%', '([^&]+)'); }
Set query vars
add_filter( 'query_vars', 'query_vars'); public function query_vars($query_vars) { $query_vars[] = 'country'; $query_vars[] = 'state'; $query_vars[] = 'city'; $query_vars[] = 'town'; return $query_vars; }
After that you can get the values by get_query_var
get_query_var
This is not tested. But with your little effort this can be helpful. LEt me know in the comments below.