我想禁用免费送货,直到在WooCommerce中的某个日期只使用PHP.

add_filter( 'woocommerce_package_rates', 'disable_free_shipping_until_certain_date', 10, 2 );

function disable_free_shipping_until_certain_date($rates, $package) {
    $current_date = date("Y-m-d");
    $disable_date = strtotime('2024-02-25');
    $disable_date = date('Y-m-d',$disable_date);
    
    if($current_date < $disable_date){
        unset( $rates['free_shipping'] );
    }
    return $rates;
}

这是我制作的PHP代码片段,但它不起作用.
为什么我无法使其工作?
我需要更改什么?

推荐答案

您需要在当前发货区为您的免费发货方式定义正确的发货费率ID (array key),才能使其在您的代码中起作用.

try 以下操作,在特定的定义日期阈值之前禁用免费送货:

add_filter( 'woocommerce_package_rates', 'disable_free_shipping_until_specific_date', 10, 2 );
function disable_free_shipping_until_specific_date( $rates, $package ) {
    $threshold_date = '2024-02-25'; // Threshold date until free shipping is disabled

    // Loop through shipping rates for the current shipping package
    foreach ( $rates as $rate_key => $rate ) {
        // Targeting free shipping and specific date
        if ( 'free_shipping' === $rate->method_id && time() <= strtotime($threshold_date) ) {
            unset($rates[$rate_key]); // Remove shipping rate
        }
    }
    return $rates;
}

代码放在子主题的functions.php文件中(或插件中).测试和作品.

Important:您必须清空购物车才能刷新发货方法缓存.

Php相关问答推荐

如何隐藏x轴图表上的值

如何优化-PHP 7.3.14+Laravel 6

如果再次调用SESSION_START(),会话.gc-max是否会重新启动?或者它是从第一次创建会话开始计算的?

如何在WooCommerce产品子类别中显示特定内容

PHP Laravel Web应用启动时间&>15秒

Laravel Carbon DiffForHumans选项(年,月,天)

Rappasoft Datatables V2(我想在另一个表具有相同值列时显示数据)

Azure应用程序无法访问共享文件夹

添加不存在的订单元数据以扩展WooCommerce针对特定产品的管理订单搜索

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

根据页面以及是否在促销,向 WooCommerce 中显示的价格添加前缀

对 WooCommerce 购物车和 checkout 中显示的运输方式进行排序

API 平台 - UI 服务器端点定义

invalid_grant 和无效的 JWT 签名

通过添加计数器修改文本区域表单中的重复值

在 DateTime 或 DateTimeImmutable 对象上调用modify() 时是否必须使用空格?

如何获得没有运输等级的产品

Xdebug 不会在断点处停止

使用 PHP 有条件地使用关键字 Twilio Programmable SMS

PHP 从 API 获取随机项目