WordPress’s permalink feature is already great and really helpful for good SEO. But sometimes you need custom variables in your url like

http://www.ptitsuisse.com/custom-variable-example/?brand=htc&model=desirehd

but this is not SEO friendly, it’s hard to remember and doesn’t look good.

http://www.ptitsuisse.com/custom-variable-example/htc/desirehd

This is better and needs only a small change to your theme functions.php file to work.

function add_url_rewrite() {
    //Add custom variables to wordpress query
    add_rewrite_tag("%brand%", '(.+)');
    add_rewrite_tag("%model%", '(.+)');
    
    //Add rewrite rule to catch the variable values
    add_rewrite_rule('^custom-variable-example/([^/]*)/([^/]*)/?','index.php?pagename=custom-variable-example&brand=$matches[1]&model=$matches[2]','top');
}
add_action( 'init', 'add_url_rewrite' );


Add this code in your functions.php file located in your theme folder. Then you need to flush your permalinks. Simply go to the permalink page in the back-end: just open the permalink page, that will flush the permalinks and activate your custom variables. No need to change anything or save, just open or refresh the page.

To use these variables in your template or posts (using a PHP plugins like Exec-PHP) simply use:

$brand = get_query_var('brand');
$model = get_query_var('model');

Be careful:

  • variable names should not match any of the post types (careful if you have a lot of custom types) or any category or tag used on your webpage
  • after any changes to the code above in your functions.php file, always flush the permalinks by going to the permalink page

Tested on WordPress 3.3+. Demo: http://www.ptitsuisse.com/custom-variable-example/htc/desirehd