在Elementor中仅显示WordPress主分类法术语可行性咨询
在Elementor中仅显示自定义文章类型的主分类术语
方法1:用Elementor内置动态标签(零代码)
- 打开Elementor编辑器,找到要放置分类的位置,添加「动态文本」或「动态术语」模块
- 点开动态标签设置,选择「分类术语」,然后在参数里调整:
- 选中你创建的自定义分类法
- 找到「术语类型」选项,选择「主术语」(部分版本显示英文「Primary Term」)
- 按需设置显示格式,比如仅显示名称,或者设置为可点击的链接
方法2:自定义短代码(灵活度更高)
如果内置标签满足不了需求,把下面的代码加到主题的functions.php文件,或是自定义插件中:
function get_post_primary_term($taxonomy = 'your_custom_taxonomy') { global $post; if (!$post) return ''; // 获取文章的主分类ID $primary_term_id = get_post_meta($post->ID, '_elementor_primary_' . $taxonomy, true); if ($primary_term_id) { $term = get_term($primary_term_id, $taxonomy); if ($term && !is_wp_error($term)) { return '<span class="primary-term">' . esc_html($term->name) . '</span>'; } } // 兜底:未设置主分类时,返回第一个分类 $terms = get_the_terms($post->ID, $taxonomy); if ($terms && !is_wp_error($terms)) { return '<span class="primary-term">' . esc_html($terms[0]->name) . '</span>'; } return ''; } add_shortcode('show_primary_term', 'get_post_primary_term');
- 把代码里的
your_custom_taxonomy替换成你实际的自定义分类法slug - 保存后,在Elementor中添加「短代码」模块,输入
[show_primary_term]即可显示主分类
方法3:用Elementor钩子(高级自定义)
要是需要在特定Elementor模块中修改输出,使用这个钩子:
function modify_elementor_term_display($terms, $settings) { // 仅针对目标自定义分类法生效 if ($settings['taxonomy'] !== 'your_custom_taxonomy') return $terms; global $post; $primary_term_id = get_post_meta($post->ID, '_elementor_primary_' . $settings['taxonomy'], true); if ($primary_term_id) { $primary_term = get_term($primary_term_id, $settings['taxonomy']); if ($primary_term && !is_wp_error($primary_term)) { return [$primary_term]; } } return $terms; } add_filter('elementor/dynamic_tags/term_terms/terms', 'modify_elementor_term_display', 10, 2);
- 同样把
your_custom_taxonomy替换成实际的分类法slug - 这个钩子会强制Elementor的术语标签只返回主分类
注意事项
- 编辑文章时,记得给自定义文章类型的内容设置「主分类」:在Elementor编辑器右侧「文档设置」-「分类」里,点击分类旁的星标即可设置
- 使用代码方法时,建议用子主题或自定义插件存放代码,避免主题更新后代码丢失
内容的提问来源于stack exchange,提问作者Cosmin Dan
相关产品推荐
相关产品推荐

