隐藏Woocommerce中特定产品的特定送货方式

时间:2018-03-29 09:28:41

标签: php wordpress woocommerce cart shipping

我的WooCommerce商店中有一些产品很重(超过20公斤),可通过某种运输方式运送。我想隐藏'shipping_method_0_flat_rate2'所有包含重量超过20公斤的产品的购物车。

我尝试调整下面的代码段,但它不完整且有效:

add_filter( 'woocommerce_package_rates', 'hide_shipping_based_on_tag' ,    10, 1 );
function check_cart_for_share() {

    // specify the product id's you want to hide
    $product_ID = array(
    '113', // Product name
    );
    global $woocommerce;
    $cart = $woocommerce->cart->cart_contents;

    $found = false;

    // loop through the array looking for the products. Switch to true if the product is found.
    foreach ($woocommerce->cart->cart_contents as $key => $values ) {
        $terms = get_the_terms( $values['product_id'], 'product_cat' );
        foreach ($terms as $term) {
            if( in_array( $term->term_id, $product_ID ) ) {

        $found = true;
        break;
    }
  }
}

return $found;

}

function hide_shipping_based_on_tag( $available_methods ) {

    // use the function above to check the cart for the products.
    if ( check_cart_for_share() ) {

    // remove the method you want
    unset( $available_methods['shipping_method_0_flat_rate2'] ); // Replace with the shipping option that you want to remove.
}

    // return the available methods without the one you unset.
    return $available_methods;

}

感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

您的代码中的内容会变得更复杂,而且您的送货方式ID不是很好...请尝试以下方法:

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

    $product_ids = array( 113 ); // HERE set the product IDs in the array
    $method_id = 'flat_rate:2'; // HERE set the shipping method ID
    $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_id] );

    return $rates;
}

代码放在活动子主题(或活动主题)的function.php文件中。经过测试和工作。

  

您需要刷新送货缓存:
  1)首先,此代码已保存在function.php文件中。
  2)在运输设置中,输入运输区域并禁用运输方式和"保存"。然后重新启用送货方式和"保存"。 你已经完成了。