WordPress查询循环中获取多自定义分类法术语填入列表data属性
实现方案
直接在单篇项目的循环逻辑中,读取当前项目对应三个分类法的关联术语,处理空值和多术语场景后,填入li的自定义属性位置即可,调整后的完整可运行代码如下:
<?php $args = array( 'post_type' => 'projets', 'posts_per_page' => 99, 'order' => 'ASC', ); $loop = new WP_Query( $args ); while ( $loop->have_posts() ) : $loop->the_post(); // 分别读取当前项目关联的三个自定义分类法术语 $city_terms = get_the_terms( get_the_ID(), 'city' ); $typo_terms = get_the_terms( get_the_ID(), 'typo' ); $statut_terms = get_the_terms( get_the_ID(), 'statut' ); // 兼容空值、多术语场景,拼接为可直接输出的字符串 $city_name = !is_wp_error( $city_terms ) && !empty( $city_terms ) ? implode( ',', wp_list_pluck( $city_terms, 'name' ) ) : ''; $typo_name = !is_wp_error( $typo_terms ) && !empty( $typo_terms ) ? implode( ',', wp_list_pluck( $typo_terms, 'name' ) ) : ''; $statut_name = !is_wp_error( $statut_terms ) && !empty( $statut_terms ) ? implode( ',', wp_list_pluck( $statut_terms, 'name' ) ) : ''; ?> <li class="content_item active" data-city="<?php echo esc_attr( $city_name ); ?>" data-typo="<?php echo esc_attr( $typo_name ); ?>" data-statut="<?php echo esc_attr( $statut_name ); ?>"> <a href="<?php the_permalink(); ?>"> <?php the_post_thumbnail('custom-size', ['class' => 'content_item_img', 'title' => 'Image du projet']); ?> <h4><?php the_title(); ?></h4> </a> </li> <?php endwhile; wp_reset_postdata(); ?>
关键逻辑说明
- 所有输出到HTML属性的值都经过
esc_attr()转义,避免术语名称中的特殊字符破坏HTML结构,符合WordPress开发的安全规范 - 提前判断了分类法绑定为空、查询返回错误的场景,对应属性值会输出空字符串,不会触发PHP运行警告
- 若单篇项目绑定了同分类下的多个术语,会自动用英文逗号拼接名称,适配前端JS筛选逻辑对data属性的常规匹配规则
- 修正了原代码中
posts_per_page的字符串传值问题,改用数字格式传参,避免参数解析出现隐式类型转换异常
内容的提问来源于stack exchange,提问作者Paulette
相关产品推荐
相关产品推荐

