I want my url to look like this www.example/events/United+States instead of how it currently looks like which is www.example/events/?country=United+States. I'm not quite sure how to go about this. Here is my code
<?php
$some_url = site_url().'/events/';
$params = array( 'country' => urlencode($counter) );
$some_url = add_query_arg( $params, $some_url );
?>
<a class="gpo_country" href="<?php echo $some_url ?>" >
I want my url to look like this www.example/events/United+States instead of how it currently looks like which is www.example/events/?country=United+States. I'm not quite sure how to go about this. Here is my code
<?php
$some_url = site_url().'/events/';
$params = array( 'country' => urlencode($counter) );
$some_url = add_query_arg( $params, $some_url );
?>
<a class="gpo_country" href="<?php echo $some_url ?>" >
Share
Improve this question
asked Oct 24, 2017 at 2:22
NaomiNaomi
32 bronze badges
2
|
1 Answer
Reset to default 0You can create a rewrite rule using add_rewrite_rule()
that will match a given path to query parameters:
function wpse_283774_rewrite() {
add_rewrite_rule( '^events/([^/]+)/?', 'index.php?pagename=events&country=$matches[1]', 'top' );
}
add_action( 'init', 'wpse_283774_rewrite' );
This rule will match whatever is after /events
as the country
query parameter. Setting the third argument to top
means that it will match our rule first, otherwise it will try to match whatever is after /events
as a child page of /events
.
Now we just need to register country
as a valid query parameter:
function wpse_283774_query_vars( $vars ) {
$vars[] = 'country';
return $vars;
}
add_filter( 'query_vars', 'wpse_283774_query_vars' );
Now in your template/functions you can get whatever comes after /events
with get_query_var( 'country' )
:
if ( get_query_var( 'country' ) ) {
echo 'Events for ' . get_query_var( 'country' );
}
Just make sure to re-save your Permalinks settings after adding the code.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744755643a4591864.html
/events
? Is it a post type archive? A page? – Jacob Peattie Commented Oct 24, 2017 at 3:12