I’m working on a wordpress project at the moment, and pushing that blogging engine quite a bit further than I have before. We’re going to be using categories very extensively and one of the first tasks has been to allow category paths without any preceding /category/ or the like. By default, wordpress wants the category with a slug of ‘case-studies’ to live at:
/category/case-studies
but we want it to be simply:
/case-studies
So far, so straightforward. I installed the pathless-category-links plugin and all was well. Until I started using subcategories. All subcategory links started returning 404s. It seems I’m far from alone in that problem, but I’ve not yet seen a solution offered, so a little digging was required.
What was happening with subcategories (at least in my setup) was that the wordpress method that parses the query string was identifying the top-level category name as the category name and the subcategory name as the ’name’ (ie. the post slug to look for). What was needed was a check to see whether that ’name’ maps to a category slug and if so, correct wordpress’ assumption.
The code I’m using is:
if (! function_exists('jys_pathless_category_links_query_string')) {
function jys_pathless_category_links_query_string($qs) {
parse_str($qs, $query_vars);
if (isset($query_vars['name']) && get_category_by_slug($query_vars['name'])) {
$res = array('category_name' => $query_vars['category_name'] . "/" . $query_vars['name']);
return http_build_query($res);
}
return $qs;
}
}
add_filter('query_string', 'jys_pathless_category_links_query_string');
(NB: This will break if you have permalinks set up as recommended by the plugin author (’/%category%/%postname%’) and a post in your top-level category with the same slug as your subcategory. But hopefully that’s rare enough that we’ll be okay!)