事实上,我很容易就能做到这一点。我现在可以在permalinks中拥有我的分类库。这允许我现在有如下URL:
http://www.new1450.dev/industries/ {Main blog post only showing category selection}
http://www.new1450.dev/industries/development/ {a parent category}
http://www.new1450.dev/industries/development/parent-category-i/ {child of parent}
http://www.new1450.dev/industries/development/parent-category-i/child-category-i/ {child of child}
http://www.new1450.dev/industries/development/parent-category-i/child-category-i/some-cool-post/ {actual post}
这应该适用于任何级别的类别嵌套。
My Permalink settings:
自定义结构:
/industries/%category%/%postname%/
类别基础:industries/.
(/.
是必需的,因为它可以防止404s用于post)
Code:
/**
* Fix 404 for permalinks using category_base
*/
function permalinkWithCategoryBaseFix() {
global $wp_query;
// Only check on 404\'s
if ( true === $wp_query->is_404) {
$currentURI = !empty($_SERVER[\'REQUEST_URI\']) ? trim($_SERVER[\'REQUEST_URI\'], \'/\') : \'\';
if ($currentURI) {
$categoryBaseName = trim(get_option(\'category_base\'), \'/.\'); // Remove / and . from base
if ($categoryBaseName) {
// Perform fixes for category_base matching start of permalink custom structure
if ( substr($currentURI, 0, strlen($categoryBaseName)) == $categoryBaseName ) {
// Find the proper category
$childCategoryObject = get_category_by_slug($wp_query->query_vars[\'name\']);
// Make sure we have a category
if (is_object($childCategoryObject)) {
$paged = ($wp_query->query_vars[\'paged\']) ? $wp_query->query_vars[\'paged\']: 1;
$wp_query->query(array(
\'cat\' => $childCategoryObject->term_id,
\'paged\'=> $paged
)
);
// Set our accepted header
status_header( 200 ); // Prevents 404 status
}
unset($childCategoryObject);
}
}
unset($categoryBaseName);
}
unset($currentURI);
}
}
add_action(\'template_redirect\', \'permalinkWithCategoryBaseFix\');
我最初有:
$childCategoryObject = get_category_by_slug( ((!empty($wp_query->query_vars[\'page\']) && $wp_query->query_vars[\'page\'] > 1) ? $wp_query->query_vars[\'category_name\'] : $wp_query->query_vars[\'name\']) );
代替:
$childCategoryObject = get_category_by_slug($wp_query->query_vars[\'name\']);
但似乎没有必要检查。我留下了这条评论,以防我记不起它的原因。。。
此外,我的默认类别分页也有问题。。。快速搜索会返回许多有相同问题的人(不会超过第2页),因此我也添加了此修复。我在WordPress插件中找到了此修复:Category pagination fix. 我更新了代码,修复如下:
/**
* Fix the problem where next/previous of page number buttons are broken of posts in a category when the custom permalink
* The problem is that with a url like this:
* /categoryname/page/2
* the \'page\' looks like a post name, not the keyword "page"
*/
function fixCategoryPagination($queryString) {
if (isset($queryString[\'name\']) && $queryString[\'name\'] == \'page\' && isset($queryString[\'page\'])) {
unset($queryString[\'name\']);
// \'page\' in the query_string looks like \'/2\', so i\'m exploding it
list($delim, $page_index) = explode(\'/\', $queryString[\'page\']);
$queryString[\'paged\'] = $page_index;
}
return $queryString;
}
add_filter(\'request\', \'fixCategoryPagination\');
Note: 应该注意的是,分页修复只在父类别上需要。子类别没有分页问题。