admin管理员组

文章数量:1406944

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
  • What is /events? Is it a post type archive? A page? – Jacob Peattie Commented Oct 24, 2017 at 3:12
  • @JacobPeattie /events is a page – Naomi Commented Oct 24, 2017 at 3:17
Add a comment  | 

1 Answer 1

Reset to default 0

You 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.

本文标签: permalinksrebuilding rewriting a url to make it SEO friendly