如何修复WordPress分类子分类显示短代码的适配问题?
WordPress短代码修复:适配任意数量子分类的分类显示
修复后的完整短代码
function display_post_category_with_children() { // 获取当前文章的分类(可根据需求调整是否排除默认分类) $categories = get_the_category(); if ( empty( $categories ) || is_wp_error( $categories ) ) { return '暂无分类'; } $output = ''; foreach ( $categories as $category ) { $output .= '<div class="category-group">'; $output .= '<strong>' . esc_html( $category->name ) . '</strong>'; // 获取当前分类的子分类 $child_categories = get_terms( array( 'taxonomy' => 'category', 'parent' => $category->term_id, 'hide_empty' => false, // 可按需设置是否显示无文章的子分类 ) ); // 处理子分类的各种场景 if ( ! empty( $child_categories ) && ! is_wp_error( $child_categories ) ) { $output .= '<ul class="child-categories">'; foreach ( $child_categories as $child ) { $output .= '<li>' . esc_html( $child->name ) . '</li>'; } $output .= '</ul>'; } elseif ( is_wp_error( $child_categories ) ) { $output .= '<span>子分类加载失败</span>'; } else { $output .= '<span>暂无子分类</span>'; } $output .= '</div>'; } return $output; } add_shortcode( 'post_category_with_children', 'display_post_category_with_children' );
关键修复点
- 错误拦截:在获取分类、子分类后,用
is_wp_error()检查是否返回错误对象,避免直接调用属性导致报错 - 兼容任意子分类数量:不再依赖固定的子分类数量,改用循环遍历所有子分类,1个、多个、0个都能正常处理
- 空状态兜底:针对无分类、无子分类、分类获取失败的场景分别添加提示,可根据需求修改或删除提示内容
- 安全输出:用
esc_html()转义分类名称,避免XSS安全风险
使用方法
把代码添加到Code Snippets插件或主题的functions.php文件中,在文章/页面里插入短代码[post_category_with_children]即可显示当前文章的分类及对应子分类。
内容的提问来源于stack exchange,提问作者Carlita Alvarez
相关产品推荐
相关产品推荐

