如何在WordPress中基于当前产品分类获取同类相似产品
完整实现代码
将以下代码添加到你的产品单页模板对应位置即可实现同分类相似产品画廊功能:
global $post; // 获取当前产品所属分类 $postcat = get_the_category( $post->ID ); // 容错处理:当前产品未分配分类时直接终止逻辑 if ( empty( $postcat ) ) { return; } // 提取分类ID数组,支持匹配多个关联分类 $cat_ids = wp_list_pluck( $postcat, 'term_id' ); // 构造同分类产品查询参数 $related_args = array( 'post_type' => 'product', // 对应你的产品自定义文章类型别名 'category__in' => $cat_ids, 'post__not_in' => array( $post->ID ), // 排除当前产品自身 'posts_per_page' => 8, // 可自定义展示的相似产品数量 'orderby' => 'date', // 排序规则,可选rand/title/comment_count等 'order' => 'DESC', 'post_status' => 'publish', // 仅查询已发布的产品 ); $related_products = new WP_Query( $related_args ); // 有匹配产品时输出画廊结构 if ( $related_products->have_posts() ) : ?> <div class="related-products-gallery"> <h3>相似产品</h3> <div class="gallery-list"> <?php while ( $related_products->have_posts() ) : $related_products->the_post(); ?> <div class="gallery-item"> <!-- 输出产品卡片,可根据需求调整结构 --> <a href="<?php the_permalink(); ?>"> <?php if ( has_post_thumbnail() ) : ?> <?php the_post_thumbnail( 'medium', array( 'alt' => get_the_title() ) ); ?> <?php endif; ?> <p class="product-title"><?php the_title(); ?></p> </a> </div> <?php endwhile; ?> </div> </div> <?php endif; // 重置主循环数据,避免影响页面其他查询逻辑 wp_reset_postdata();
注意事项
- 如果你用的是自定义分类法(例如WooCommerce默认的产品分类
product_cat,而非系统默认的分类),需要将获取分类的代码替换为:
同时将查询参数里的$postcat = get_the_terms( $post->ID, 'product_cat' ); // 第二个参数替换为你的自定义分类法别名category__in替换为tax_query参数:$related_args = array( // 其他原有参数保持不变 'tax_query' => array( array( 'taxonomy' => 'product_cat', // 对应自定义分类法别名 'field' => 'term_id', 'terms' => $cat_ids, ) ), // 移除原有`category__in`参数 ); - 代码中
posts_per_page的数值可自行调整,控制相似产品的展示数量 - HTML结构和类名可根据你的模板现有样式修改,匹配你的画廊UI设计
内容的提问来源于stack exchange,提问作者lulu
相关产品推荐
相关产品推荐

