Steven
Steven

Reputation: 19425

How can I create (custom) friendly URL in Wordpress?

In Wordpress, I have set the permalink structure like this: /%category%/%postname%

After creating a custom search page, I now have the following URL:
http://mypage.com/search?foo1=bar&foo2=&foo3=&foo4=

I have two questions:

1) How can I transform this url so that I get to e.g. http://mypage.com/search/foo1/bar ?

2) Is there a way I can remove the "unused" parameters? (&foo2=&foo3=&foo4=)

I found this post, pointing me to parse_request function in Wordpress, and this post talking about mod_rewrite. But not quite sure how to proceed, or what method is better to use.

Upvotes: 0

Views: 573

Answers (2)

user12352274
user12352274

Reputation:

You can use rewrite rules,

Here is a simple example of how to register a new rewrite rule, and pass it off to a PHP file for rendering:

1. Setup a rule:

add_action( 'init',  function() {
    add_rewrite_rule( 'myparamname/([a-z0-9-]+)[/]?$', 'index.php?myparamname=$matches[1]', 'top' );
} );

2. Flush permalinks. Go to WP Admin > Settings > Permalinks > Save. This doesn’t happen automatically after you add this code

3. Whitelist the query param:

add_filter( 'query_vars', function( $query_vars ) {
    $query_vars[] = 'myparamname';
    return $query_vars;
} );

4. Add a handler to send it off to a template file:

add_filter( 'template_include', function( $template ) { if ( get_query_var( 'myparamname' ) == false || get_query_var( 'myparamname' ) == '' ) { return $template; }

return get_template_directory() . '/template-name.php';

} );

See: https://developer.wordpress.org/reference/functions/add_rewrite_rule/#comment-3503

Upvotes: 0

Pragati Sureka
Pragati Sureka

Reputation: 1412

you can use both the methods parse_request() function of wordpress or mod_rewrite for transforming your url, but for that to work properly you will have to write a function that catches the requested url and translates it into original url to serve the request.

Upvotes: 0

Related Questions