我尝试使用不同的代码从 Woocommerce 购物车页面隐藏送货方式。这些代码一直有效,直到我从购物车中删除产品为止。一旦我删除产品,运输部分就会返回。刷新页面后,它再次工作。
我尝试过的代码之一:
add_filter( 'woocommerce_cart_needs_shipping', 'filter_cart_needs_shipping' );
function filter_cart_needs_shipping( $needs_shipping ) {
if ( is_cart() ) {
$needs_shipping = false;
}
return $needs_shipping;
}
我也尝试过这段代码:
function disable_shipping_calc_on_cart( $show_shipping ) {
if( is_cart() ) {
return false;
}
return $show_shipping;
}
add_filter( 'woocommerce_cart_ready_to_calc_shipping', 'disable_shipping_calc_on_cart', 99 );
我将代码放在我的主题 function.php 文件中。两个代码的问题是相同的。
我使用 WordPress 6.5.2、WooCommerce 8.8.3 和二十二十四主题。
这个问题如何解决?
要禁用 woocommerce 购物车页面上的发货,以下代码适用于基于 woocommerce 模板的购物车页面。
add_filter( 'woocommerce_cart_needs_shipping', 'filter_cart_needs_shipping' );
function filter_cart_needs_shipping( $needs_shipping ) {
if ( is_cart() ) {
$needs_shipping = false;
}
return $needs_shipping;
}
但是对于基于 woocommerce 块的购物车页面,当购物车项目在购物车页面上更新时,此代码不起作用。这是由于以下原因:在基于 woocommerce 块的购物车页面上,使用 woocommerce 商店 API 更新购物车项目。因此,在基于 woocommerce 块的购物车页面上的购物车更新请求期间, is_cart() 函数调用的返回值为“false”。要禁用基于 woocommerce 块的购物车页面上的发货,可以使用以下代码。
add_filter( 'woocommerce_cart_needs_shipping', 'filter_cart_needs_shipping' );
function filter_cart_needs_shipping( $needs_shipping ) {
if ( is_cart() ) {
$needs_shipping = false;
}
return $needs_shipping;
}
add_filter( 'rest_pre_dispatch', function( $result, $server, $request ) {
if ( str_contains( $request->get_route(), '/wc/store/v1/cart/remove-item' ) || str_contains( $request->get_route(), '/wc/store/v1/cart/update-item' ) ) {
add_filter( 'woocommerce_cart_needs_shipping', '__return_false');
}
return $result;
}, 10, 3 );