如何在WooCommerce循环中仅隐藏分组商品的子商品
解决方案:仅隐藏WooCommerce循环中的分组商品子商品
原方案错误地将分组父商品也排除了,我们可以通过调整查询条件,只筛选出作为分组商品子项的简单商品并排除它们,同时保留分组父商品。
修改后的代码如下:
add_action( 'woocommerce_product_query', 'exclude_grouped_product_children_from_loops' ); function exclude_grouped_product_children_from_loops( $q ) { if ( ! is_admin() && $q->is_main_query() ) { // 获取所有属于分组商品子项的简单商品ID $child_product_ids = get_posts( array( 'post_type' => 'product', 'post_status' => 'publish', 'fields' => 'ids', 'meta_query' => array( array( 'key' => '_parent_id', 'value' => '0', 'compare' => '>', 'type' => 'numeric' ) ), 'tax_query' => array( array( 'taxonomy' => 'product_type', 'field' => 'slug', 'terms' => 'simple', ) ) ) ); if ( ! empty( $child_product_ids ) ) { $q->set( 'post__not_in', $child_product_ids ); } } }
代码说明
- 利用
woocommerce_product_query钩子修改商品主查询,仅在前台生效(排除后台操作场景) - 通过
meta_query筛选出存在父商品ID的商品(即分组子项),再通过tax_query限定为简单商品,避免误删分组父商品 - 将这些子商品ID加入
post__not_in参数,从商品循环中排除
使用方法:将代码添加到当前主题的functions.php文件,或自定义功能插件中即可。
内容的提问来源于stack exchange,提问作者Jay
相关产品推荐
相关产品推荐

