我试图隐藏所有其他运输方法有条件的,如果一个特定的存在.

以下是我的代码:

function hide_shipping_when_alg_wc_shipping_31_is_present( $rates, $package ) {
    // Check if alg_wc_shipping:31 is present
    $alg_wc_shipping_31_present = false;
    foreach ( $package->get_shipping_items() as $item ) {
        if ( $item->needs_shipping() && $item->get_shipping_class() === 'alg_wc_shipping:31' ) {
            $alg_wc_shipping_31_present = true;
            break;
        }
    }

    // If alg_wc_shipping:31 is present, hide alg_wc_shipping:30 and alg_wc_shipping:29
    if ( $alg_wc_shipping_31_present ) {
        foreach ( $rates as $rate_key => $rate ) {
            if ( in_array( $rate->get_method_id(), array( 'alg_wc_shipping:30', 'alg_wc_shipping:29' ) ) ) {
                unset( $rates[ $rate_key ] );
            }
        }
    }
    return $rates;
}
add_filter( 'woocommerce_package_rates', 'hide_shipping_when_alg_wc_shipping_31_is_present', 10, 2 );

但这并不管用. 有人能告诉我这个代码出了什么问题吗?

我试了几种方法,但都不管用.

推荐答案

如果有特定的送货方式,您的代码真的可以简化为隐藏其他送货方式:

add_filter( 'woocommerce_package_rates', 'hide_others_except_specific_shipping_method', 10, 2 );
function hide_others_except_specific_shipping_method( $rates, $package ) {
    // Define the specific shipping method to keep if present
    $targeted_method_rate_id = 'alg_wc_shipping:31';

    if ( isset($rates[$targeted_method_rate_id]) ) {
        return array( $targeted_method_rate_id => $rates[$targeted_method_rate_id] );
    }
    return $rates;
}

代码放在活动子主题(或活动主题)的函数.php文件中.经过测试,效果良好.

Important:您必须清空购物车才能刷新运输方式缓存.

Php相关问答推荐

无法使用PHP DomDocument找到IMG元素

允许Laravel路由指定`withTrashed`,尽管有显式的模型绑定

在WooCommerce产品档案页面中显示产品销售百分比

在函数内部获取一致的单选按钮值以更新WordPress用户数据

如何让PHP变量跨越多个脚本调用?

在Google云存储对象上从PHP设置缓存控制TTL会更改错误的元数据

筛选器具有多个查询之一

如何在execute语句中使用存储过程参数?

创建一个Woocommerce我的帐户订单页面,仅显示已完成的订单

表单提交返回空白页

如何在 apache Laragon - laravel 10 中允许方法 DELETE?

Woocommerce 仅在前端为登录用户提供价格折扣

使用 secure 和 httponly 选项删除 php 中的 cookie 值得吗?

使用 Composer 找不到 Google APIClient 类

在 WooCommerce 我的帐户自定义部分显示未购买的产品

WooCommerce - 调用功能ID不正确.不应直接访问订单属性

为 WordPress 页面创建新功能

PHP preg_replace括号和方括号内的所有逗号

使用来自 PHP 表单的数据更新 xml 命名空间

Laravel 查询关系是否为 bool