* Photo by Michael Fertig
Authors in WordPress have a homepage url like http://domain.com/author/authorname where all their posts are shown. And many of us who think it doesn’t look attractive want to change that url format. The middle part of that url, which says author, is called an author_base and it is possible to change this using some rewrite rules and filters. Let’s get our hand dirty π
Modifying the permalink
To change the author base in permalink, you need to use the global $wp_rewrite
class, like this
add_action("init","change_author_base_in_permalink"); function change_author_base_in_permalink() { global $wp_rewrite; $wp_rewrite->author_base = "users"; $wp_rewrite->flush_rules(); }
Now, as soon as you visit http://domain.com/author/authorname you will see that it’s a 404. Good, eh? At the same time, this link http://domain.com/users/authorname will display all the posts for this particular user.
If you want to revert this change and go back to the old url structure, then all you have to do is comment that action, and then flush the permalink for once.
Other fixes
There is one small problem. Though the new permalink has been effective, but get_author_posts_url() still returns an url with the old format. So we need to fix that part too. Luckily, there is a filter π
add_filter("author_link","fix_author_link"); function fix_author_link($link){ if($link){ return str_replace("author","users",$link); } }
That’s mainly it. I hope you find this article useful.
Very handy! π
Flushing the rewrite rules is an expensive operation, executing it on the
init
hook is a bad practice. Flushing rules only should be run on plugin activation or deactivation.Thanks for your comment, Tareq. To be honest, if we both speak benchmarks, soft flush using $wp_rewrite->flush_rules() is not that expensive. One hundred soft flush call takes like 0.00078201293945312 seconds. And surprisingly, 100 get_the_category_list() takes 45 times more than that, 0.035834074020386 seconds in total. So you can see that a single get_the_category_list() call, which is pretty common and frequently used, is actually 45 times more expensive than a soft flush.
Now I agree that this should be done from a plugin, precisely from the plugins_loaded or register_activation_hook and hard flushing would be best, but for the demonstration purpose of the whole thing to show how it works, it’s not bad attaching it in the init hook.
And when it comes about cost, I totally don’t agree that a soft flush is expensive. It’s not. Not at all π