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

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


With Permalinks off your page looks like

And is basically the same as

With Permalinks on

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


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 =
‘^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 *