WordPress:如何在特定项目归档页的指定Div添加分类术语CSS类
给Elementor循环网格中的项目容器添加分类术语CSS类
问题背景
需要在ID为1690的项目归档页(使用Elementor循环网格展示项目)中,为每个项目对应的指定Div(data-id="ee4ea21"的容器)添加该项目关联的所有分类术语作为CSS类,用于实现页面筛选功能。
目标Div结构:
<div class="elementor-element elementor-element-ee4ea21 e-con-boxed e-con" data-id="ee4ea21" data-element_type="container">
此前尝试的测试JS代码未生效:
function emoe_add_class_to_div() { if(is_page( 1690 ) ) { echo "<script>$(document).ready(function(){ var ediv = document.querySelector('[data-id=\"ee4ea21\"]'); ediv.classList.add(\"trish\"); });</script>"; } } add_action ('wp' ,'emoe_add_class_to_div' );
另有一段给body标签添加分类类的代码,无法直接适配目标Div:
add_filter( 'body_class', 'themeprefix_add_taxonomy_class' ); // Add taxonomy terms name to body class function themeprefix_add_taxonomy_class( $classes ){ if( is_singular() ) { global $post; $taxonomy_terms = get_the_terms($post->ID, 'your_taxonomy'); // change to your taxonomy if ( $taxonomy_terms ) { foreach ( $taxonomy_terms as $taxonomy_term ) { $classes[] = 'tax_' . $taxonomy_term->slug; } } } return $classes; }
解决方案
1. 修复测试用JavaScript代码
原JS失效原因包括:jQuery无冲突模式未处理、元素可能动态加载、选择器仅匹配第一个元素。修改后的代码:
function emoe_add_test_class() { if ( is_page(1690) ) { ?> <script> // 适配WordPress jQuery无冲突模式 jQuery(document).ready(function($) { // 遍历所有目标容器添加测试类 $('[data-id="ee4ea21"]').each(function() { $(this).addClass('trish'); }); }); // 处理Elementor动态渲染的情况 setTimeout(function() { jQuery('[data-id="ee4ea21"]').addClass('trish'); }, 1000); </script> <?php } } add_action('wp_footer', 'emoe_add_test_class');
说明:将钩子从wp改为wp_footer,确保脚本在页面底部加载;用jQuery代替$,适配WordPress的无冲突设置;添加延迟处理应对动态渲染的元素。
2. 后端添加分类术语类(推荐方案)
直接通过Elementor钩子在渲染容器时添加类,避免前端延迟问题,精准匹配每个循环项目:
步骤1:替换分类法slug
将代码中的your_taxonomy替换为实际使用的分类法标识(例如project_category)。
步骤2:添加PHP代码
将以下代码添加到主题的functions.php文件或自定义插件中:
// 给Elementor循环中的指定容器添加分类术语类 add_action('elementor/frontend/container/before_render', 'emoe_add_taxonomy_classes_to_elementor_container', 10, 2); function emoe_add_taxonomy_classes_to_elementor_container($container, $args) { // 仅在目标页面生效 if ( !is_page(1690) ) return; // 匹配目标容器的data-id $target_data_id = 'ee4ea21'; if ( $container->get_id() !== $target_data_id ) return; // 获取当前循环的文章对象 global $post; if ( !$post ) return; // 获取文章关联的分类术语 $taxonomy = 'your_taxonomy'; // 替换为你的分类法slug $terms = get_the_terms($post->ID, $taxonomy); if ( !empty($terms) && !is_wp_error($terms) ) { foreach ( $terms as $term ) { // 添加格式为tax_{分类slug}的CSS类 $container->add_render_attribute('_wrapper', 'class', 'tax_' . $term->slug); } } }
验证效果
刷新页面后,查看项目容器的HTML代码,会看到类似tax_web-design tax-branding的分类类已添加到目标Div中。
内容的提问来源于stack exchange,提问作者Trisht
相关产品推荐
相关产品推荐

