Enable only free shipping method for a specific custom field value in Woocommerce

旧巷老猫 提交于 2020-01-05 03:56:16

问题


I'm trying to add code like the one below into functions.php file. The overall function is to check products in cart and their custom fields (post_meta) called auto_delivery_default.

If its certain text in the custom field then display free shipping only, if all other text then show all other shipping methods.

Here's what I've gotten so far but I'm overlooking something making it not function right;

function show_free_ship_to_autodelivery ( $autodelivery_rate ) {
$autodelivery_free = array();

foreach( WC()->cart->get_cart() as $cart_item ){
$product = $cart_item['data'];
$product_id = $product->get_id(); // get the product ID

$autodelivery = get_post_meta( $product->get_id(), 'auto_delivery_default', true );

    if( $autodelivery == "90 Days" ) {
            $autodeliveryfree = array();
            foreach ( $rates as $rate_id => $rate ) {
                if ( 'free_shipping' === $rate->method_id ) {
                    $autodelivery_free[ $rate_id ] = $rate;
                    break;
                }
            }
            return ! empty( $autodelivery_free ) ? $autodelivery_free : $autodelivery_rate;
    }
}
}

add_filter( 'woocommerce_package_rates', 'show_free_ship_to_autodelivery', 10);

回答1:


There is some errors and mistakes in your code… Instead, try the following that will hide other shipping methods when free shipping is available and when a cart item with a custom field auto_delivery_default has a value of 90 Days:

add_filter( 'woocommerce_package_rates', 'show_only_free_shipping_for_autodelivery', 100, 2 );
function show_only_free_shipping_for_autodelivery ( $rates, $package ) {
    // Loop through cart items
    foreach( $package['contents'] as $cart_item ){
        if( $cart_item['data']->get_meta('auto_delivery_default') == '90 Days' ) {
            $found = true;
            break; // Stop the loop
        }
    }

    if( ! ( isset($found) && $found ) )
        return $rates; // Exit

    $free = array();
    foreach ( $rates as $rate_id => $rate ) {
        if ( 'free_shipping' === $rate->method_id ) {
            $free[ $rate_id ] = $rate;
            break;
        }
    }
    return ! empty( $free ) ? $free : $rates;
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.



来源:https://stackoverflow.com/questions/52412946/enable-only-free-shipping-method-for-a-specific-custom-field-value-in-woocommerc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!