Home > database >  How to show specific shipping options
How to show specific shipping options

Time:02-05

How can I show to my user on the checkout page a specific shipping option ?

I know how to remove a shipping option but I can't add a new one (an existing one) in $rates.

I tried to add :

array_push($rates, 'flat_rate:5');

Isn't array_push supposed to do the job ?

Here is a basic snippet, from my function files.

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

    $total = WC()->cart->cart_contents_total;

    if( $total < 100 ) {

      // remove from shipping options
      unset( $rates['advanced_free_shipping'] );

      // Tryed it but critical error is thrown
      array_push($rates, 'flat_rate:5');
    }

    return $rates;
} 

Tried everybit of code that I found on stack and other places, seems I'm the only one to have an issue...

CodePudding user response:

$rates is not a simple array, it contains also an object with data for each rate, so adding an array incl. the object is something you want to avoid. But you don't need to. Instead you can do it like this:

...
if( $total < 100 ) {
  // remove from shipping options
  unset( $rates['advanced_free_shipping'] );
}
else {
  // only available when total is <= 100
  unset( $rates['flat_rate:5'] );
}
...

It basically does the same.

  • Related