【问题标题】:Hide multiple shipping methods based on product IDs in WooCommerce在 WooCommerce 中隐藏一组基于产品 ID 的运输方式
【发布时间】:2021-12-15 16:43:30
【问题描述】:

如果在 WooCommerce 上选择了一组产品,我想隐藏一组运输方式

我想我快到了,但我在 unset( $rates[$method_ids] ) 行上遇到错误。

这是我目前所得到的:

add_filter( 'woocommerce_package_rates', 'specific_products_shipping_methods_hide_many', 10, 2 );
function specific_products_shipping_methods_hide_many( $rates, $package ) {

    $product_ids = array( 240555 ); // HERE set the product IDs in the array
    $method_ids = array( 'flat_rate:7', 'flat_rate:13', 'flat_rate:26', 'flat_rate:27', 'local_pickup:24' ) ; // HERE set the shipping method IDs
    $found = false;

    // Loop through cart items Checking for defined product IDs
    foreach( $package['contents'] as $cart_item ) {
        if ( in_array( $cart_item['product_id'], $product_ids ) ){
            $found = true;
            break;
        }
    }
    if ( $found )
        unset( $rates[$method_ids] );

    return $rates;
}

有什么建议吗?

【问题讨论】:

  • $rates[$method_ids] 中方法 ID 看起来是一个数组。
  • 有没有办法获取这些数组值并将其保存在 $rates[] 中?
  • 您想取消设置method_ids 数组中的所有ID?然后,您需要遍历该数组。还是只有一个值?你能澄清一下吗?目前,您的错误是因为您无法取消设置 $rates 中的值数组。

标签: php wordpress woocommerce shipping-method


【解决方案1】:

你很接近,但你需要循环通过$rates,如果它发生$rate_id,你可以取消它

所以你得到:

function filter_woocommerce_package_rates( $rates, $package ) {
    // Set the product IDs in the array
    $product_ids = array( 240555, 30 );
    
    // Set the rate IDs in the array
    $rate_ids = array( 'flat_rate:7', 'flat_rate:13', 'flat_rate:26', 'flat_rate:27', 'local_pickup:24', 'local_pickup:1', 'free_shipping:2' );
    
    // Initialize
    $found = false;

    // Loop through cart items checking for defined product IDs
    foreach( $package['contents'] as $cart_item ) {
        // Checks if a value exists in an array
        if ( in_array( $cart_item['product_id'], $product_ids ) ) {
            $found = true;
            break;
        }
    }
    
    // True
    if ( $found ) {
        // Loop trough
        foreach ( $rates as $rate_id => $rate ) {
            // Checks if a value exists in an array
            if ( in_array( $rate_id, $rate_ids ) ) {
                unset( $rates[$rate_id] );
            }
        }
    }
    
    return $rates;
}
add_filter( 'woocommerce_package_rates', 'filter_woocommerce_package_rates', 10, 2 );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-08
    • 2020-08-25
    • 2022-06-18
    • 2015-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多