permalinks - rebuilding rewriting a url to make it SEO friendly

I want my url to look like this www.exampleeventsUnited+Statesinstead of how it currently looks like which is www.exa

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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744755643a4591864.html

相关推荐

  • permalinks - rebuilding rewriting a url to make it SEO friendly

    I want my url to look like this www.exampleeventsUnited+Statesinstead of how it currently looks like which is www.exa

    5小时前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信