如何为WordPress Elementor博客的分类添加自定义类或ACF参数?
给Elementor分类链接添加自定义类/ACF字段的解决方案
方案1:添加分类ID/别名作为自定义类
Elementor提供了专门的过滤器修改分类链接的类名,直接在主题的functions.php文件或自定义插件中添加以下代码:
add_filter( 'elementor/post/terms_list/item_classes', 'add_category_id_to_elementor_term_links', 10, 3 ); function add_category_id_to_elementor_term_links( $classes, $term, $taxonomy ) { // 仅针对文章分类(category)生效,其他分类法可自行修改 if ( 'category' !== $taxonomy ) { return $classes; } // 添加分类ID类(格式:cat-{ID}) $classes[] = 'cat-' . $term->term_id; // 可选:添加分类别名类(格式:cat-{slug}) $classes[] = 'cat-' . $term->slug; return $classes; }
添加后,分类链接代码会变成:
<span class="elementor-post-info__terms-list"> <a href="https://website.nl/culture/" class="elementor-post-info__terms-list-item cat-45 cat-culture">Culture</a> </span>
之后就可以用CSS针对特定分类设置颜色:
/* 按分类ID设置 */ .cat-45 { color: #2ecc71; } /* 按分类别名设置 */ .cat-culture { color: #3498db; }
方案2:添加ACF自定义字段到分类链接
如果你已经用ACF给分类创建了自定义字段(比如字段名category_color,用来存颜色值或类名),可以用过滤器把字段值添加为类名或data属性:
示例1:添加ACF字段值作为自定义类
add_filter( 'elementor/post/terms_list/item_classes', 'add_acf_class_to_elementor_term_links', 10, 3 ); function add_acf_class_to_elementor_term_links( $classes, $term, $taxonomy ) { if ( 'category' !== $taxonomy ) { return $classes; } // 获取分类的ACF字段值(替换成你的字段名) $acf_class = get_field( 'category_color_class', 'category_' . $term->term_id ); if ( $acf_class ) { $classes[] = $acf_class; } return $classes; }
示例2:添加ACF颜色值作为data属性
如果ACF字段存的是具体颜色值,也可以直接添加data属性方便CSS使用:
add_filter( 'elementor/post/terms_list/item_attributes', 'add_acf_color_data_to_elementor_term_links', 10, 3 ); function add_acf_color_data_to_elementor_term_links( $attributes, $term, $taxonomy ) { if ( 'category' !== $taxonomy ) { return $attributes; } // 获取ACF颜色字段值(替换成你的字段名) $color = get_field( 'category_color', 'category_' . $term->term_id ); if ( $color ) { $attributes['data-category-color'] = $color; } return $attributes; }
此时分类链接会变成:
<span class="elementor-post-info__terms-list"> <a href="https://website.nl/culture/" class="elementor-post-info__terms-list-item" data-category-color="#3498db">Culture</a> </span>
对应的CSS写法:
.elementor-post-info__terms-list-item { color: attr(data-category-color); }
内容的提问来源于stack exchange,提问作者Jordy
相关产品推荐
相关产品推荐

