如何在WooCommerce中列出指定产品分类下的所有可见商品
如何在WooCommerce中列出指定产品分类下的所有可见商品
嘿,我来帮你搞定这个需求!你要展示指定分类(比如slug为smart-shoes)下的所有可见商品,之前的代码是在获取分类数据,但我们其实可以直接查询该分类下的产品,这样更直接高效。下面给你两种靠谱的实现方法:
方法一:用WooCommerce专属的WC_Product_Query(推荐)
这个方法是WooCommerce官方推荐的,专门针对产品查询,能自动处理商品的可见性规则,非常省心:
// 配置查询参数 $args = array( 'status' => 'publish', // 只取已发布的可见商品,自动排除草稿、下架、私密商品 'category' => array('smart-shoes'), // 填你要指定的分类slug,支持多个分类(比如array('slug1', 'slug2')) 'orderby' => 'title', 'order' => 'ASC', 'limit' => -1, // 设置为-1表示显示所有商品,想限制数量就改成具体数字(比如10) ); // 初始化产品查询 $products = new WC_Product_Query($args); $product_list = $products->get_products(); // 输出商品列表 if (!empty($product_list)) { echo '<ul class="category-products-list">'; foreach ($product_list as $product) { // 安全获取商品标题和链接 $product_title = esc_html($product->get_name()); $product_link = esc_url($product->get_permalink()); echo "<li><a href='$product_link'>$product_title</a></li>"; } echo '</ul>'; } else { echo '<p>这个分类下暂时没有可见商品哦~</p>'; }
参数说明:
'status' => 'publish':确保只抓取前台可见的已发布商品,自动过滤掉后台设置为隐藏、下架的商品'limit' => -1:不限制商品数量,一次性展示所有符合条件的商品- 如果你想按其他规则排序,比如按价格或上架日期,把
orderby改成price或date就行
方法二:用WordPress原生WP_Query
如果你更习惯用WordPress原生的查询类,也可以这么写,效果一样:
$args = array( 'post_type' => 'product', // 指定查询产品类型 'post_status' => 'publish', // 只取已发布商品 'tax_query' => array( array( 'taxonomy' => 'product_cat', // 目标分类法是产品分类 'field' => 'slug', // 用slug来匹配分类 'terms' => 'smart-shoes', // 要查询的分类slug 'operator' => 'IN', ) ), 'orderby' => 'title', 'order' => 'ASC', 'posts_per_page' => -1, // 显示所有商品 ); $product_loop = new WP_Query($args); // 输出商品列表 if ($product_loop->have_posts()) { echo '<ul class="category-products-list">'; while ($product_loop->have_posts()) { $product_loop->the_post(); global $product; $title = esc_html(get_the_title()); $link = esc_url(get_permalink()); echo "<li><a href='$link'>$title</a></li>"; } echo '</ul>'; // 一定要重置查询,避免影响后续内容 wp_reset_postdata(); } else { echo '<p>这个分类下暂时没有可见商品哦~</p>'; }
小提示:
- 你可以把这段代码放到主题的模板文件里(比如分类页面模板
category-product.php,或者自定义页面模板),也可以封装成短码,这样在后台编辑页面/文章时直接插入短码就能调用啦 - 如果想通过分类ID来查询,只需要把
'field' => 'slug'改成'field' => 'term_id',然后'terms'填对应的分类ID就行
内容来源于stack exchange
相关产品推荐
相关产品推荐

