WooCommerce显示“再购X件享折扣”的shortcode在侧边购物车不自动刷新如何解决
WooCommerce自定义折扣提示短code侧边AJAX购物车不更新解决方案
问题原因
默认购物车页面修改商品数量时,会触发WooCommerce默认的购物车区块全局刷新,你的短code如果在刷新范围内就会同步更新。但侧边AJAX购物车仅刷新自身预设的内容区块,不会主动重渲染你自定义的短code输出内容,因此计数不会变动。
实现方案
我们可以借助WooCommerce内置的**购物车碎片(cart fragments)**机制实现自动刷新,该机制会在购物车内容变动时自动更新你提前注册的自定义DOM节点内容,无需编写完整的AJAX请求逻辑。
步骤1:修改原有PHP代码
将你现有的短代码替换为以下内容:
add_shortcode('check', 'custommessage'); function custommessage() { $items_count = WC()->cart->get_cart_contents_count(); $min_count = 6; // 用专属DOM容器包裹输出内容,方便定位刷新 $output = '<div class="wc-discount-remaining-notice">'; if( $items_count < $min_count ){ $output .= sprintf('再购买%s件商品即可获得折扣', $min_count - $items_count ); } else { // 满足折扣条件时输出空,可自行修改为达标提示 $output .= ''; } $output .= '</div>'; // 注意:WordPress短代码必须return输出内容,不可直接echo,否则会出现输出位置错误 return $output; } // 将自定义提示块注册到WooCommerce自动刷新碎片列表 add_filter( 'woocommerce_add_to_cart_fragments', 'refresh_discount_notice_fragment' ); function refresh_discount_notice_fragment( $fragments ) { $fragments['div.wc-discount-remaining-notice'] = custommessage(); return $fragments; }
步骤2:兼容自定义侧边购物车(可选)
绝大多数主题的侧边AJAX购物车都会在内容更新后触发WooCommerce默认的updated_cart_totals事件,只要触发该事件,上面注册的提示块就会自动刷新。如果测试后仍不更新,可以在侧边购物车的JS更新逻辑执行完成后,手动添加一行触发事件的代码:
jQuery(document.body).trigger('updated_cart_totals');
说明
如果需要调整最低购买件数、提示文本,直接修改custommessage函数中的$min_count变量和输出文本即可。
内容的提问来源于stack exchange,提问作者Uxell
相关产品推荐
相关产品推荐

