Custom URL structure in Wordpress using filters and hooks

December 13, 2011

Wordpress, as we all know is one of the greatest open source website platforms available right now and what with it being open source and all that pretty much anything is possible with it.

You just need to dig deep enough and most of the time you'll find the answer. I was looking for a simple way to rewrite a custom url to a page within wordpress.

I wanted to recreate a url like this dashboard/authorise/2/ with the 2 being an id for the object I am trying to authorise.

My page called 'authorise' with a page parent of dashboard would look out for the presence of the passed parameter and use it within the page to attempt an authorisation request for that object.

After alot of digging I found the answer within Wordpress.

In the end I needed to use a combination of 3 hooks although one is not necessarily 100% necessary. All of the below snippets should reside in your functions.php wordpress theme file.

function flush_rewrite(){
    global $wp_rewrite;
add_action('init', 'flush_rewrite');

This function simply flushes the Wordpress re-write rules to the database. The second hook adds the expected parameter to the Wordpress query vars filter and is required so that our page can pull the variable out later.

function add_wp_query_vars($public_query_vars){
    $public_query_vars[] = 'auth_id';
    return $public_query_vars;
add_filter('query_vars', 'add_wp_query_vars');	

The third and final hook is to the "generate_rewrite_rules" hook, and it allow us to add a custom Wordpress re-write rule for our new URL structure.

function authorise_rewrite_rules($wp_rewrite){
    $wp_rewrite->rules = array(
        'dashboard/authorise/(.*)/?' => 'index.php?pagename=authorise&auth_id='.$wp_rewrite->preg_index(1)
    ) + $wp_rewrite->rules;
add_action('generate_rewrite_rules', 'authorise_rewrite_rules');

As you can see i've included the full url including the parent of the page and re-written the arguments to auth_id. The final bit of information you now need to know is how to get this variable for usage on your page, its quite simple really.

global $wp_query;
echo 'Auth_id: '.$wp_query->get('auth_id');

Note: You do not have to use pagename like I have in my rewrite rule you could be using the "page_id" method instead, I just prefer pagename as it's a bit more universal across installs. There you have it a simple way to keep nice URL's within Wordpress.

About me

Hello! I'm David Heward, how are you going? I'm a Senior Devops/Build Engineer, specialising in AWS & Cloud Automation. Based in London. Strong 10+ year background in Software development. Have a read of my blog. Have a look at some of my working projects. Contact me at @davehewy or on Linkedin.