WordPress如何调用WooCommerce全量产品标签实现custom loop标签筛选
WooCommerce产品标签调用与带筛选的自定义循环实现方案
获取所有已使用的WooCommerce产品标签
WooCommerce的产品标签本质是WordPress自定义分类法product_tag,直接通过get_terms函数即可调用所有生效标签:
// 获取所有已关联产品的标签 $all_product_tags = get_terms( array( 'taxonomy' => 'product_tag', 'hide_empty' => true, // 设为false可展示未关联任何产品的空标签 'orderby' => 'name', 'order' => 'ASC' ) ); // 遍历输出标签的基础用法 if ( ! is_wp_error( $all_product_tags ) && ! empty( $all_product_tags ) ) { foreach ( $all_product_tags as $tag ) { echo '<a href="' . get_term_link( $tag ) . '">' . esc_html( $tag->name ) . '</a>'; } }
支持标签筛选的自定义产品循环
可以通过URL参数传递标签slug,在自定义查询中加入筛选条件,完整示例代码如下:
// 1. 获取筛选参数(可自定义参数名,示例用product_tag_filter) $filter_tag_slug = isset( $_GET['product_tag_filter'] ) ? sanitize_text_field( $_GET['product_tag_filter'] ) : ''; // 2. 配置基础产品查询参数 $args = array( 'post_type' => 'product', 'posts_per_page' => 12, // 每页展示产品数量 'post_status' => 'publish', ); // 3. 存在筛选标签时追加分类法查询条件 if ( ! empty( $filter_tag_slug ) ) { $args['tax_query'] = array( array( 'taxonomy' => 'product_tag', 'field' => 'slug', 'terms' => $filter_tag_slug, 'operator' => 'IN' ) ); } // 4. 执行查询输出循环 $custom_product_loop = new WP_Query( $args ); if ( $custom_product_loop->have_posts() ) { while ( $custom_product_loop->have_posts() ) { $custom_product_loop->the_post(); // 此处替换为你自己的产品卡片输出逻辑,也可以调用WooCommerce默认产品模板 wc_get_template_part( 'content', 'product' ); } // 分页输出逻辑 echo paginate_links( array( 'total' => $custom_product_loop->max_num_pages ) ); } else { echo '<p>没有找到符合条件的产品</p>'; } // 重置查询,避免影响页面其他默认查询 wp_reset_postdata();
- 如需支持多选标签筛选,只需把标签参数改为数组形式,调整
$_GET参数接收逻辑为数组格式,同时把tax_query的terms字段改为接收到的slug数组即可 - 以上代码可直接放在自定义页面模板、产品归档页模板或者主题函数文件的对应钩子位置使用
内容的提问来源于stack exchange,提问作者Eliolas
相关产品推荐
相关产品推荐

