如何使用短代码筛选并仅显示WooCommerce简单产品
解决WooCommerce短代码仅显示简单产品的问题
问题根源
原代码存在两个核心问题:
- 短代码注册的函数名
simple_product_list和实际定义的函数名simple_list_shortcode不匹配,导致短代码无法正常执行,这大概率是页面白屏的直接原因。 - 未处理
wc_get_product()返回false的情况(比如产品已被删除但仍在查询结果中),会触发致命错误导致白屏。
解决方案一:查询时直接筛选简单产品(推荐)
直接在WP_Query中通过meta_query过滤产品类型为simple的产品,无需循环内二次判断,性能更优:
add_shortcode('product_list', 'simple_product_list'); function simple_product_list() { $query = new WP_Query( array( 'posts_per_page' => -1, 'post_type' => 'product', 'post_status' => 'publish', 'orderby' => 'title', 'order' => 'ASC', // 补充明确的排序方向 'meta_query' => array( array( 'key' => '_product_type', 'value' => 'simple' ) ) ) ); $output = '<ul style="list-style-type:none">'; if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); $product = wc_get_product( get_the_ID() ); // 跳过无效产品 if ( ! $product ) continue; $price = $product->get_regular_price(); $output .= '<li>' . get_the_title() . ' costs '. wc_price( $price ) . ', <a class="atc" href="'. esc_url( $product->add_to_cart_url() ) .'">order now</a>.</li>'; endwhile; wp_reset_postdata(); else : $output .= '<li>No simple products found.</li>'; endif; return $output . '</ul>'; }
解决方案二:循环内判断产品类型
如果需要保留原有查询逻辑,可在循环内添加产品类型判断,同时修正错误避免白屏:
add_shortcode('product_list', 'simple_product_list'); function simple_product_list() { $query = new WP_Query( array( 'posts_per_page' => -1, 'post_type' => 'product', 'post_status' => 'publish', 'orderby' => 'title', 'order' => 'ASC' ) ); $output = '<ul style="list-style-type:none">'; if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); $product = wc_get_product( get_the_ID() ); // 跳过非简单产品或无效产品 if ( ! $product || ! $product->is_type('simple') ) continue; $price = $product->get_regular_price(); $output .= '<li>' . get_the_title() . ' costs '. wc_price( $price ) . ', <a class="atc" href="'. esc_url( $product->add_to_cart_url() ) .'">order now</a>.</li>'; endwhile; wp_reset_postdata(); else : $output .= '<li>No products found.</li>'; endif; return $output . '</ul>'; }
关键修改说明
- 修正了短代码注册与函数名不匹配的问题,确保短代码能正确触发函数。
- 方案一通过
meta_query直接从数据库层面筛选简单产品,减少循环内的逻辑判断,提升执行效率。 - 添加产品对象有效性检查,避免因无效产品引发的致命错误。
- 使用
get_the_title()替代直接调用$query->post->post_title,符合WordPress编码规范。 - 用
esc_url()处理添加到购物车的链接,避免URL注入风险。
内容的提问来源于stack exchange,提问作者Thomas Burrows
相关产品推荐
相关产品推荐

