WP: get_author_posts_url() in MU with sub-directories

Just a little tip here. We did a project with a multi site setup with sub directories. There was a photo blog on blogs.example.com/photo/, a food blog on blogs.example.com/food/ and the main/default site gets blogs.example.com/blog/ by default by WordPress. On the main site we wanted a list of the latest posts across the network. A couple of UNION SELECTs solved the data fetching. A loop with switch_to_blog() solved The Loop. But we had a problem with get_author_posts_url(). For some reason it added the default /blog/ sub-directory to all blogs. So instead of blogs.example.com/photo/author/feedmeastraycat/ we got blogs.example.com/blog/photo/author/feedmeastraycat/.

I guess the “problem” here is that switch_to_blog() doesn’t change the WP_Rewrite object. So when get_author_posts_url() calls $wp_rewrite->get_author_permastruct() it get’s the permalink for the main site blog plus the permalink for the selected blog.

Not sure if this is a bug. Or just a way that it have to work. Either way, I created a filter for author_link which solved the problem for us.

function my_author_link($link, $author_id, $author_nicename) {
	global $blog_id;
	if (is_main_site($blog_id)) {
		return $link;
	else {
		return str_replace("/blog/author/", "/author/", $link);
add_filter('author_link', 'my_author_link', 11, 3);

What we do here is getting the global $blog_id variable which contains the current blog’s id number. We run it through is_main_site() to see if this is for example the photo blog, or the food blog, or if it is the main site. If isn’t the main site, we do a string replace on /blog/author/ to just be /author/. But if it’s any other site we return the $link parameter as it is, unchanged.

Disclaimer: Not sure if the problem exists if you don’t have permalink structure. Haven’t even tested. :)

Posted by David — Share: http://fmasc.net/3bo
Post new comment to WP: get_author_posts_url() in MU with sub-directories

Advance users: Click to view allowed XHTML tags.