Last Updated: February 25, 2016
·
6.588K
· saif_cse

Wordpress custom URL rewrites and tips

Wordpress has its own URL rewrite support for custom development. Before starting code, it would be good to visit its codex page here. Though there are many things to know and will take time to understand the whole process, i'm describing here a common scenario for rewriting a URL.

htaccess can be used to rewrite URL's and good technical knowledge required for that to do that on server, at this point we can use wp rewrite to fullfill our need without editing site's htaccess file.

Here goes the things: suppose we have a page for news listing like http://example.com/news, and we added a custom field in back-end to choose a news reporter. Now we want a page where news will be listed by reporter. we also need SEO friendly URL like this: http://example.com/news/reporter. In this case if we can take reporter slug from URL like \index.php?pagename=catalog&reporter=john',we can the get reporter slug and can use for further query.

Normally all rewrite rules map to a file handler (almost always index.php), not another URL.

add_filter('rewrite_rules_array','wp_insertMyRewriteRules');
add_filter('query_vars','wp_insertMyRewriteQueryVars');

// Adding a new rule
function wp_insertMyRewriteRules($rules)
{
    $newrules = array();
    $newrules['news/(.*)/?'] = 'index.php?pagename=news&reporter=$matches[1]';
    return $newrules + $rules;
}

// Adding the 'reporter' var so that WP recognizes it
function wp_insertMyRewriteQueryVars($vars)
{
    array_push($vars, 'reporter');
    return $vars;
}

This would map news/whatever to the WordPress page 'news', and pass along the query var 'reporter'. You could create a page template for 'news', then pick up the value of 'reporter' using getqueryvar('reporter').

In above example, first we wrote the rules and added the function, then added function to get it by query var.

Tips:

1. Avoid using query vars like id - use something more unique (like 'reporter') to avoid clashes with WordPress.
2. Don't flush rules on every init! It's bad practice, and will write to .htaccess and call database updates on every page load!
3. WordPress will always flush permalinks whenever you update a post or your permalink structure (simply update your permalinks when you make changes to your code).

Will be back soon with another WP issue :)

*Original post here in my personal blog: http://saifthegreen.com/wordpress-custom-url-rewrites-and-tips/