In WooCommerce shop I have 2 delivery method based on Parcel locker. The first is payable in advance, while the second is cash on delivery.
The idea is:
- easypack_parcel_machines -> only Pay in advance
- easypack_parcel_machines_cod -> only Cash on delivery
My code below. After applying in both cases, I only have Pay in advance. What’s wrong?
add_filter( 'woocommerce_available_payment_gateways', 'gateway_disable_shipping_meth' ); function gateway_disable_shipping_meth( $available_gateways ) { if ( ! is_admin() ) { $chosen_methods = WC()->session->get( 'chosen_shipping_methods' ); $chosen_shipping = $chosen_methods[0]; if ( isset( $available_gateways['bacs'] ) && 0 === strpos( $chosen_shipping, 'easypack_parcel_machines' ) ) { unset( $available_gateways['cod'] ); } elseif ( isset( $available_gateways['cod'] ) && 0 === strpos( $chosen_shipping, 'easypack_parcel_machines_cod' ) ) { unset( $available_gateways['bacs'] ); } } return $available_gateways; }
Advertisement
Answer
As both shipping methods start with the same slug, you should simply need to invert them in your if / elseif statement as follows (also there are some other mistake):
add_filter( 'woocommerce_available_payment_gateways', 'gateway_disable_shipping_meth' ); function gateway_disable_shipping_meth( $available_gateways ) { if ( ! is_admin() ) { $chosen_shipping = WC()->session->get( 'chosen_shipping_methods' )[0]; if ( isset( $available_gateways['bacs'] ) && 0 === strpos( $chosen_shipping, 'easypack_parcel_machines_cod' ) ) { unset( $available_gateways['bacs'] ); } elseif ( isset( $available_gateways['cod'] ) && 0 === strpos( $chosen_shipping, 'easypack_parcel_machines' ) ) { unset( $available_gateways['cod'] ); } } return $available_gateways; }
or also this way too:
add_filter( 'woocommerce_available_payment_gateways', 'gateway_disable_shipping_meth' ); function gateway_disable_shipping_meth( $available_gateways ) { if ( ! is_admin() ) { $chosen_shipping = WC()->session->get( 'chosen_shipping_methods' )[0]; if ( 0 === strpos( $chosen_shipping, 'easypack_parcel_machines' ) ) { if ( false !== strpos( $chosen_shipping, 'cod' ) && isset( $available_gateways['bacs'] ) ) { unset( $available_gateways['bacs'] ); } elseif ( isset( $available_gateways['cod'] ) ) { unset( $available_gateways['cod'] ); } } } return $available_gateways; }
It should work.