在构建电影站、小说站、下载站等需要复杂内容组织的 WordPress 网站时,自定义文章类型和自定义分类法(Custom Taxonomies)是必不可少的工具。它们常与多级筛选功能配合使用。虽然筛选文章相对容易,但如何在文章页面或模板中正确调用自定义分类的名称及其链接,却是一个常见的技术难点。
核心概念与注意事项
自定义分类法允许你为文章或自定义文章类型创建独立于默认“分类”和“标签”之外的分类体系,例如为“电影”类型创建“类型”、“导演”、“演员”等分类。
重要提示: 以下方法主要适用于同时使用了自定义文章类型和自定义分类法的场景。如果你在默认的“文章”类型上使用自定义分类法,直接调用分类链接时,可能会遇到“404页面不存在”的错误。这是因为 WordPress 默认的固定链接规则可能没有为这种组合生成正确的重写规则,通常需要通过代码(如 flush_rewrite_rules())或在插件中重新保存固定链接设置来解决。
获取自定义分类名称与链接的代码实现
以下是一个功能完善的函数示例,它不仅能获取文章所属的自定义分类,还能智能地区分父级分类和子级分类,并输出带有正确链接的分类名称。我们以自定义文章类型 movie 及其分类法 types 为例。
步骤一:将函数添加到主题
将以下代码放入你当前主题的 functions.php 文件中。
/**
* 获取文章的自定义分类法层级(名称与链接)
*
* @param int $post_id 文章ID,默认为当前文章。
* @param string $taxonomy 自定义分类法名称。
* @param string $separator 多个子分类间的分隔符,默认为逗号加空格。
* @param bool $echo 是否直接输出,默认为 true。如果为 false 则返回字符串。
* @return string|void 返回分类链接的HTML字符串,或直接输出。
*/
function get_taxonomy_hierarchy_links( $post_id = null, $taxonomy = 'types', $separator = ', ', $echo = true ) {
// 如果未指定文章ID,则使用全局 $post 对象
if ( null === $post_id ) {
global $post;
if ( ! $post ) {
return '';
}
$post_id = $post->ID;
}
// 获取文章关联的所有分类项
$terms = wp_get_post_terms( $post_id, $taxonomy );
if ( is_wp_error( $terms ) || empty( $terms ) ) {
return '';
}
$output = '';
$parent_term = null;
$child_terms = array();
// 分离父级分类和子级分类
foreach ( $terms as $term ) {
if ( 0 == $term->parent ) {
$parent_term = $term;
} else {
$child_terms[] = $term;
}
}
// 输出父级分类链接
if ( $parent_term ) {
$parent_link = get_term_link( $parent_term, $taxonomy );
if ( ! is_wp_error( $parent_link ) ) {
$output .= sprintf( '%s', esc_url( $parent_link ), esc_html( $parent_term->name ) );
}
}
// 输出子级分类链接
if ( ! empty( $child_terms ) ) {
$child_links = array();
foreach ( $child_terms as $child_term ) {
$child_link = get_term_link( $child_term, $taxonomy );
if ( ! is_wp_error( $child_link ) ) {
$child_links[] = sprintf( '%s', esc_url( $child_link ), esc_html( $child_term->name ) );
}
}
if ( ! empty( $child_links ) ) {
// 如果存在父级,则在父级后添加分隔符
if ( $parent_term ) {
$output .= ' / ';
}
$output .= implode( $separator, $child_links );
}
}
if ( $echo ) {
echo $output; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
} else {
return $output;
}
}
步骤二:在主题模板中调用
在你希望显示分类名称和链接的地方(例如 single-movie.php 或 content-single.php),插入以下调用代码。
<div class="movie-taxonomy-types">
<span class="label">类型:</span>
<?php get_taxonomy_hierarchy_links( null, 'types' ); ?>
</div>
代码解析与优化说明
- 函数封装: 我们将功能封装成一个可复用的函数,并添加了详细的参数说明,提高了代码的灵活性和可维护性。
- 错误处理: 使用
is_wp_error()检查wp_get_post_terms()和get_term_link()的返回值,避免因分类不存在或链接生成失败而导致页面错误。 - 安全性: 使用
esc_url()和esc_html()对输出的URL和文本进行转义,防止跨站脚本攻击。 - 逻辑清晰: 明确分离了父级分类和子级分类的处理逻辑,输出格式为“父级分类 / 子分类1,子分类2”。
- 返回值选项: 通过
$echo参数,你可以选择让函数直接输出结果,或者将结果作为字符串返回以便进行进一步处理。
通过以上方法,你可以稳健地在 WordPress 主题中调用任何自定义分类法的名称和链接,无论是单级还是多级分类结构都能完美适配。