'Display specific shipping method if woocommerce product has specific acf field value

I need display specific shipping methods only if specific acf checkbox in product is checked. I created custom field viac ACF plugin with name "zpusob_prepravy". It is set to checkbox and has 3 values - "cp", "ppl", "dpd". Also I created via woocommerce->settings->shipping->shipping zones 3 shipping methods (ČP, PPL, DPD).

If is only acf checkbox "cp" checked in product, only "ČP" shipping method should display in cart and checkout pages, and so on.

I have used code below, but it doesn't work.

function filter_woocommerce_package_rates( $rates, $package ) {

    $field = get_field('zpusob_prepravy');

    // Multiple can be added, separated by a comma
    $exclude = array( 'flat_rate:1' );

    // Loop through
    foreach ( $rates as $rate_key => $rate ) {
        // Targeting
        if( $field && in_array('cp', $field) ) {
           unset( $rates[$shipping_id ] );
        }
    }

    return $rates;
}
add_filter( 'woocommerce_package_rates','filter_woocommerce_package_rates', 10, 2 );


Solution 1:[1]

You need to check with ACF function and unset the shipping.I hope this will help you.

 <?php

add_filter( 'woocommerce_package_rates', 'define_default_shipping_method', 10, 2 );
   
function define_default_shipping_method( $rates, $package ) {
$shipping_id = 'table_rate_shipping_first-class';
$colors = get_field('name_of_your_feild');
if( $colors && in_array('cp', $colors) ) {
   unset( $rates[$shipping_id ] ); // you need to unset here other shipping methods
}
     
return $rates;
  
}

?>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Karan Mehta