
WPPOP开发的B2C外贸商城独立在模板程序,都有内置 WooCommerce 迷你购物车小部件,放置在页面右侧悬浮模块内,可以方便地实时查看购物车中的商品列表和基本属性。但是同样的模板有时在不同环境下可能会出现迷你购物车打开不显示购物车中的商品,内容空白的情况。
经过排查,和不同版本的 WooCommerce 插件有关,在较新版本中WooCommerce 默认没有加载 Cart Fragments 脚本(wc-cart-fragments)导致的。
问题原因:
- 模板中的迷你购物车通过
the_widget( 'WC_Widget_Cart' )在wp_footer里输出; - Cart Fragments 脚本(
wc-cart-fragments)完全没有被加载; - 页面上不存在
wc_cart_fragments_params这个变量; - 所以
.widget_shopping_cart_content在页面加载时是空的,只有点击 Add to cart 触发其他逻辑时才会临时出现内容。
这是 WooCommerce 7.8 之后的经典兼容问题:主题用 the_widget() 方式输出购物车时,WooCommerce 检测不到,就不会自动加载 fragments 脚本。
解决方案:
把下面代码完整放到主题的 functions.php 中,或者之前模板中调用 the_widget( 'WC_Widget_Cart' ); 的位置。
/**
* 强制加载 WooCommerce Cart Fragments(解决 POPShop / WPPOP 主题迷你购物车空白问题)
*/
add_action( 'wp_enqueue_scripts', function() {
if ( ! class_exists( 'WooCommerce' ) ) {
return;
}
wp_enqueue_script( 'wc-cart-fragments' );
}, 20 );
/**
* 页面加载后强制刷新迷你购物车
*/
add_action( 'wp_footer', function() {
if ( ! class_exists( 'WooCommerce' ) ) {
return;
}
?>
<script>
jQuery(function($) {
// 清除可能残留的旧数据
try {
sessionStorage.removeItem('wc_fragments');
sessionStorage.removeItem('wc_cart_hash');
sessionStorage.removeItem('woocommerce_cart_hash');
} catch(e) {}
// 强制触发刷新
$(document.body).trigger('wc_fragment_refresh');
});
</script>
<?php
}, 99 );
/**
* 确保弹窗购物车内容能被正确更新
*/
add_filter( 'woocommerce_add_to_cart_fragments', function( $fragments ) {
ob_start();
echo '<div class="widget_shopping_cart_content">';
woocommerce_mini_cart();
echo '</div>';
$fragments['div.widget_shopping_cart_content'] = ob_get_clean();
return $fragments;
}, 20 );
检查生效:
- 把上面代码加到主题模板文件中;
- 清除所有缓存(网站缓存插件、浏览器缓存、CDN缓存等);
- 在后台 WooCommerce → 状态 → 工具 中,点击 清除客户会话 和 清除瞬态缓存 等临时数据;
- 打开网站,添加几个商品到购物车中;
- 刷新页面或切换到其他页面,看迷你购物车是否能直接显示商品。



