如何在Elementor中显示特定文章关联的自定义分类标签?
解决方案
方法1:自定义短代码输出当前文章关联的自定义标签
在主题的functions.php文件或自定义插件中添加以下代码,替换其中的your_custom_tag_taxonomy为你通过Custom Post Type UI创建的自定义标签分类的slug(可在CPT UI的分类设置页找到):
function get_current_post_custom_tags() { $taxonomy = 'your_custom_tag_taxonomy'; global $post; if ( !$post ) return ''; $tags = get_the_terms( $post->ID, $taxonomy ); if ( empty( $tags ) || is_wp_error( $tags ) ) return ''; $output = '<ul class="custom-post-tags">'; foreach ( $tags as $tag ) { $tag_link = get_term_link( $tag, $taxonomy ); $output .= '<li><a href="' . esc_url( $tag_link ) . '">' . esc_html( $tag->name ) . '</a></li>'; } $output .= '</ul>'; return $output; } add_shortcode( 'current_post_custom_tags', 'get_current_post_custom_tags' );
完成后,在Elementor编辑器中添加短代码小部件,输入[current_post_custom_tags]即可。单文章页面会自动显示当前文章关联的自定义标签,你可以通过自定义CSS为.custom-post-tags类设置样式(如背景色、圆角、间距等)。
方法2:通过过滤器适配Elementor动态标签
如果想复用Elementor现有组件,可在functions.php中添加以下代码,同样替换your_custom_tag_taxonomy为你的分类slug:
function filter_elementor_dynamic_tag_custom_tags( $value, $tag ) { if ( $tag->get_name() !== 'custom_post_tags' ) return $value; $taxonomy = 'your_custom_tag_taxonomy'; global $post; if ( !$post ) return ''; $tags = get_the_terms( $post->ID, $taxonomy ); if ( empty( $tags ) || is_wp_error( $tags ) ) return ''; $tag_list = array(); foreach ( $tags as $tag_term ) { $tag_link = esc_url( get_term_link( $tag_term, $taxonomy ) ); $tag_list[] = "<a href='{$tag_link}'>" . esc_html( $tag_term->name ) . "</a>"; } return implode( ' | ', $tag_list ); } add_filter( 'elementor/dynamic_tag/render_content', 'filter_elementor_dynamic_tag_custom_tags', 10, 2 );
之后在Elementor中添加文本小部件,打开动态标签面板,创建一个新的自定义动态标签(命名为custom_post_tags),即可在文本中插入该动态标签,显示带链接的标签列表,分隔符可自行修改代码中的' | '。
注意事项
- 修改
functions.php前请备份文件,或使用子主题存放自定义代码,避免主题更新时代码丢失。 - 确保自定义标签分类的slug输入正确,否则无法获取关联标签数据。
内容的提问来源于stack exchange,提问作者Jeff Wirth
相关产品推荐
相关产品推荐

