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
Thanks for this great tip.
I used this before but with a much more complicated method. This looks so easy. Will give it a try.
Is there a particular thing to add in .htaccess to make this working ?
I use WP 3.3.2 with URL rewriting.
I have added my function and the add_action in function.php and I’m not able to retrieve my variable ‘member’ with
$memberid = get_query_var('member');
in my Template page.Do I miss something ?
Nothing to add to your .htaccess file. The WordPress function added to the functions.php file takes care of all the URL rewrites.
Try to add something like
var_dump( $wp_query->query_vars );
to your header.php file to display all the variable in the query. If your “member” variable is not in the list try to:– change your variable name to something different (and not common) like “custom_member_id” (I noticed that using some variable names like custom post types or category names can be tricky, but I’m not sure about all the implications here so using something really different from common variable names)
– don’t forget to open the permalink page to apply the latest changes