Woocommerce:按指定shop_location筛选含商品的产品分类求助
问题分析与修正方案
你的代码核心问题在于混淆了**自定义文章类型(CPT)和分类法(Taxonomy)**的概念,同时tax_query的用法完全错误:
shop_location是你定义的CPT,不是分类法,无法通过tax_query直接关联产品分类;tax_query中不存在name参数,且$category->slug未定义,逻辑混乱;get_terms的tax_query是筛选分类本身的属性,无法实现“关联指定门店的商品所属分类”的需求。
修正后的代码
假设你的商品通过自定义字段(比如_shop_location)关联shop_location类型的门店帖子,以下代码可以实现需求:
<?php // 1. 获取"伦敦"对应的shop_location帖子ID $london_location = get_page_by_title('伦敦', OBJECT, 'shop_location'); if (!$london_location) { echo '未找到伦敦门店'; return; } $location_id = $london_location->ID; // 2. 查询所有关联该门店的商品(仅获取ID提升性能) $products = get_posts(array( 'post_type' => 'product', 'posts_per_page' => -1, 'post_status' => 'publish', 'meta_query' => array( array( 'key' => '_shop_location', // 替换为你实际的门店关联字段键名 'value' => $location_id, 'compare' => '=', ) ), 'fields' => 'ids', )); if (empty($products)) { echo '该门店暂无商品'; return; } // 3. 提取这些商品关联的所有产品分类ID并去重 $category_ids = array(); foreach ($products as $product_id) { $product_cats = wp_get_post_terms($product_id, 'product_cat', array('fields' => 'ids')); $category_ids = array_merge($category_ids, $product_cats); } $category_ids = array_unique($category_ids); if (empty($category_ids)) { echo '该门店商品无对应分类'; return; } // 4. 获取并展示产品分类 $product_categories = get_terms(array( 'taxonomy' => 'product_cat', 'orderby' => 'name', 'order' => 'asc', 'include' => $category_ids, 'hide_empty' => false, // 若要隐藏无商品的分类,改为true )); if (!empty($product_categories)) { echo '<ul>'; foreach ($product_categories as $category) { echo '<li><a href="' . esc_url(get_term_link($category)) . '">' . esc_html($category->name) . '</a></li>'; } echo '</ul>'; } ?>
关键注意事项
- 请将代码中的
_shop_location替换为你实际用来关联商品与门店的自定义字段键名; - 如果你的
shop_location是自定义分类法(而非CPT),只需将第一步获取门店ID的逻辑改为通过分类法获取:
并将第二步的$london_term = get_term_by('name', '伦敦', 'shop_location'); if (!$london_term) { echo '未找到伦敦门店分类'; return; }meta_query替换为tax_query即可。
内容的提问来源于stack exchange,提问作者Brad
相关产品推荐
相关产品推荐

