Rewriting URLs in WordPress

I am trying to solve a rewrite problem but don’t fully understand how to read the below code.

I believe the event/industry/(.+)/?$' is stating the format I want in my new url after rewritten, which should be example.com/event/industry/someterm/

And this part appears to be the parameter. => 'index.php?post_type=eg_event&industry=' . $wp_rewrite->preg_index(1)

Is this a correct understanding?

What is telling this code what value to place in my new url where this is: (.+)/?$' Is it the $wp_rewrite->preg_index(1) and what exactly does the preg_index(1) mean?

$new_rules = array(
'event/industry/(.+)/?$' => 'index.php?post_type=eg_event&industry=' . $wp_rewrite->preg_index(1)
);
$wp_rewrite->rules = $new_rules + $wp_rewrite->rules;
}

Any assistance you can provide with helping me understand the logic above it much appreciated.

1 Answer
1

'event/industry/(.+)/?$'

The above is the URL that will be rewritten behind the scenes. The brackets create what is known as a “backreference”.

'index.php?post_type=eg_event&industry=' . $wp_rewrite->preg_index(1)

The above is the actual URL that will be served to the browser.

So, http://yourdomain.com/event/industry/abc/ matches the rule “event/industry/(.+)/?$”. The term ‘abc’ becomes a backreference with index 1, because it matches the term enclosed in brackets.

When someone browses to that URL, the server will then silently rewrite that URL to “index.php?post_type=eg_event&industry=abc”, and serve that page instead. This “rewrite” is not visible to the browser/end-user.

$wp_rewrite->preg_index(1) simply refers to backreference with index 1.

You can have multiple backreferences. For instance:

event/(.+)/(.+)/?$

Now this rule will match http://yourdomain.com/event/magic/def/.

This time, “magic” becomes backreference with index 1, while “def” becomes backreference with index 2.

So you could rewrite the rule to:

index.php?post_type=eg_event&' . $wp_rewrite->preg_index(1) . '=' . $wp_rewrite->preg_index(2)

i.e. index.php?post_type=eg_event&magic=def

Leave a Comment