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