如果 WooCommerce 中存在特定的运输方式,则隐藏其他运输方式

问题描述 投票:0回答:1

如果存在特定的运输方式,我会尝试有条件地隐藏所有其他运输方式。

这是我的代码:

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 );

但是它不起作用。 有人可以告诉我这段代码有什么问题吗?

我尝试了很多方法,但根本不起作用。

php wordpress woocommerce hook-woocommerce shipping-method
1个回答
0
投票

如果特定的运输方式可用,您的代码确实可以简化以隐藏其他运输方式:

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;
}

代码位于活动子主题(或活动主题)的functions.php 文件中。已测试并有效。

重要提示:您必须清空购物车才能刷新运输方式缓存。

© www.soinside.com 2019 - 2024. All rights reserved.