I am looping through all the categories, getting the link, and if it is a subcategory I use a regular expression to replace the last / with a #.
# Code to display category links
foreach(wp_list_categories() as $category) {
$name = $category->name;
$link = get_category_link($category->term_id);
if($category->parent) {
// Parent isn't 0, lets change this link to have an anchor
$link = preg_replace('~/([^/]+)/?$~', '#$1', $link);
}
// Output $name/$link
}
The regex /([^/]+)/?$ matches a /, followed by any non / characters in a capture group (the anchor), followed by an optional trailing slash and the end of the string ($). We can replace this match with a pound and the anchor saved in our first capture group (#$1).
Update:
As a prefix, I can't tell from the documentation whether or not get_the_category() gets the current category for a category template..but let us assume it does. Then you can do something like this:
# Code to redirect away from subcategory pages
$category = get_the_category(); // not sure if this works
// We are directly accessing a child category, redirect
if($category->parent) {
$link = get_category_link($category->term_id);
$link = preg_replace('~/([^/]+)/?$~', '#$1', $link);
header("HTTP/1.1 301 Moved Permanently");
header("Location: $link");
exit;
}
Links: