Create rewrite rules for friendly url for WordPress plugin custom queries

I have this personal web application that was built from scratch last year and has already been considerably indexed by google. I used some Apache mod rewrite to make the urls friendly. Last week I decided it would be faster/easier to jumpstart the project again if I just focus on my application and just use a framework to handle other intricacies like abstractions, security and etc. I was aiming for CodeIgniter but got a glimpse on BuddyPress for WordPress(not a framework) which has most of the features I want for my app. So long story short I ended up porting my application to be a plugin for WordPress.


One thing that got me stuck for awhile was how to recreate my old URLs. Posting some tips for an example on how I got the issue solved.

Target: Make WordPress rewrite this URLs

http://www.thesite.com/mypage/food/
to
http://www.thesite.com/mypage/?ingredients=food

http://www.thesite.com/mypage/food/asia/
to
http://www.thesite.com/mypage/?ingredients=food&origin=asia

Steps for the solution.

1. Create your plugin and create a shortcode

(eg. add_shortcode('myapp', 'myfunction'); )

2. Create a new Page and add the shortcode

[myapp]

With Permalinks off your page looks like

http://www.thesite.com/?page_id=5

And is basically the same as

http://www.thesite.com/index.php?page_id=5

With Permalinks on

http://www.thesite.com/mypage/

3. If you pass a query on your app the URL may look like this, Im passing the queries on the URL

http://www.thesite.com/mypage/?ingredients=food

or

http://www.thesite.com/mypage/?ingredients=food&origin=asia

Depending on the queries passed the contents on your page changes.

4. Now to rewrite the URLs to be friendly you need to add a filter and use query_vars

add_filter(‘query_vars’, ‘my_query_vars’);
function my_query_vars($public_query_vars) {
$public_query_vars[] = “ingredients”;
$public_query_vars[] = “origin”;
return $public_query_vars;
}

This ensure that when WordPress parses the URL, the ingredients and origin gets saved in the query variables.

4. Next is create your rewrite rules and store in an array

add_filter(‘generate_rewrite_rules’, ‘my_rewrite’);

function my_rewrite($wpdb_rewrite) {
$wpdb_rewrite->rules =
array_merge(array
(
‘^mypage/([^/]+)/?$’ => ‘index.php?page_id=5e&ingredients=$matches[1]’,
‘^mypage/([^/]+)/([^/]+)/?$’ => ‘index.php?page_id=5&ingredients=$matches[1]&origin=$matches[2]’

), $wpdb_rewrite->rules);
}

Note: That you are rewriting to the original URL of the page. You are storing each rewrite rule to an array and finally adding them to a filter by generate_rewrite_rules.

5. To get the variables back just call the get_query_vars function on your plugin.

echo get_query_var(‘ingredients’);

So this is how I got my problem solved. Hopefully it would be a great help to others. Happy rewriting and coding!

Leave a Reply

Your email address will not be published. Required fields are marked *