wordpress - Wordpress - 父类别和所有子类别的自定义模板页面
问题描述
在 WP 5.4.2 中,我想为一个类别及其所有子类别创建一个自定义存档页面。我知道模板文件层次结构:
1. category-slug.php
2. category-ID.php
3. category.php
4. archive.php
5. index.php
但是,如果我理解正确并且所有测试都正确,则category-slug.php
或category-id.php
方案适用于单个类别,而与类别层次结构无关。
假设我有以下类别:
colors (id 2)
- red (id 10)
- green (id 11)
- blue (id 12)
我需要所有这些模板文件。简单地创建category-colors.php
或category-2.php
不起作用。它仅适用于单一类别(颜色)。我希望它适用于所有当前的子类别,以及我将来添加的所有子类别。可能吗?如果是这样,请建议如何。
解决方案
有几种方法可以做到这一点,但使用category_template
过滤器让您使用自定义类别模板似乎是最常见的。
下面的函数将让您动态地检查当前类别的父级别,直到找到一个名为“category- [parent slug] ”的模板,用于最接近的祖先类别,或者它到达顶层 - 以先到者为准。
假设你有类似的东西:
- products
- hardware
- food
- dairy
- vegetables
- 在乳制品页面上,它会首先检查您是否有一个名为
category-dairy.php
. - 如果你这样做,它将返回它。
- 如果你不这样做,它会寻找
category-food.php
. - 如果没有找到,它将寻找
category-products.php
.
将此添加到您的functions.php - 这是未经测试的代码有很好的注释,因此您可以了解它是如何工作的:
function get_template_for_category( $template ) {
if ( basename( $template ) === 'category.php' ) { // No custom template for this specific term, let's find it's parent
// get the current term, e.g. red
$term = get_queried_object();
// check for template file for the page category
$slug_template = locate_template( "category-{$term->slug}.php" );
if ( $slug_template ) return $slug_template;
// if the page category doesn't have a template, then start checking back through the parent levels to find a template for a parent slug
$term_to_check = $term;
while ( $term_to_check ->parent ) {
// get the parent of the this level's parent
$term_to_check = get_category( $term_to_check->parent );
if ( ! $term_to_check || is_wp_error( $term_to_check ) )
break; // No valid parent found
// Use locate_template to check if a template exists for this categories slug
$slug_template = locate_template( "category-{$term_to_check->slug}.php" );
// if we find a template then return it. Otherwise the loop will check for this level's parent
if ( $slug_template ) return $slug_template;
}
}
return $template;
}
add_filter( 'category_template', 'get_template_for_category' );
参考:
推荐阅读
- linq - 使用 LINQ 或 Fluent 将父子列表选择到视图模型中
- c++ - std::function 如何使指向成员函数的指针起作用?
- cmake - 从 cmake 可执行文件中获取所有包含文件夹
- r - 计算R中数据框中不同列中的独立值
- sql - 如何根据条件在两个表之间建立连接,以保留每个表中的特定记录
- java - 如何通过zuul或任何api网关调用安全的微服务端点
- java - Java Hamcrest Matcher 检查列表是否包含另一个列表
- c# - 对象不会在正确的位置生成
- javascript - ngx-spinner 不适应页面变大
- oauth-2.0 - 使用 Cognito 进行 OAuth 身份验证