Tudor Ravoiu
Tudor Ravoiu

Reputation: 2150

Wordpress rewrite rules and custom optional arguments in url

I am trying to build a filtering functionality for a Wordpress website using add_rewrite_rules. I have the following link example

 example.com/offers-type-all-inclusive-from-germany-transportation-airplane.html

Using the following rewrite rule:

add_rewrite_rule('^offers-type-?([a-z0-9-]+)?-from-?([a-z-]+)?-transportation-?([a-z0-9-]+)?.html','index.php?filters=offers&type=$matches[1]&location=$matches[2]&transportation=$matches[3]','top');

I managed to redirect the user to a custom page template with the arguments stored as an array

array(
    'type' => 'all-inclusive',
    'from' => 'germany',
    'transportation' => 'airplane'
     );

The problem is that some of the arguments could be optional so that links like

example.com/offers-type-all-inclusive-from-germany.html
example.com/offers-type-all-inclusive-transportation-airplane.html

also need to build the correct filtering array.

Is it even possible to achieve this?

Upvotes: 1

Views: 667

Answers (1)

Vasili Syrakis
Vasili Syrakis

Reputation: 9591

What a tricky regex!

Try this expression

offers-type-([a-z0-9-]*?)(?:-from-([a-z-]*?))?(?:-transportation-([a-z0-9-]*?))?\.html

Here is an online demonstration

http://regex101.com/r/fS4xB7

Upvotes: 2

Related Questions