I want to disable the payment method, cash on delivery (COD) between 11pm (current day) to 8am (next day), in my WooCommerce store.
Based on some research, this is my code attempt:
add_filter( 'woocommerce_available_payment_gateways', 'payment_gateways_based_on_hour', 1 );
function payment_gateways_based_on_hour( $gateways ) {
date_default_timezone_set('America/Lima');
if ( isset( $gateways['cod'] ) && date('H') >= 23 && date('H') <= 8 ) {
unset( $gateways['cod'] );
}
return $gateways;
}
Disabling the payment method works, but the time range is applied incorrectly, because the time span is pm/am (current day/next day) and not am/pm (same day, which does work)
Any advice on applying it to pm/am (current day/next day)?
CodePudding user response:
The woocommerce_available_payment_gateways
is a first step in the right direction. However, because you have an overlap of one night, a somewhat more extensive approach is needed.
I have added an array in my answer in which multiple payment methods can be added. However, this can also be limited to 1 specific.
To avoid problems (error) in WooCommerce backend, use if ( is_admin() ) return $payment_gateways;
.
So you get:
function the_time_range() {
// Set the correct time zone (http://php.net/manual/en/timezones.php)
date_default_timezone_set( 'Europe/Brussels' );
// Settings
$start_time = '11:00 pm';
$end_time = '08:00 am';
$date1 = DateTime::createFromFormat( 'H:i a', date( 'h:i a' ) )->getTimestamp();
$date2 = DateTime::createFromFormat( 'H:i a', $start_time )->getTimestamp();
$date3 = DateTime::createFromFormat( 'H:i a', $end_time )->getTimestamp();
if ( $date3 < $date2 ) {
$date3 = 24 * 3600;
if ( $date1 < $date2 ) {
$date1 = 24 * 3600;
}
}
if ( $date1 > $date2 && $date1 < $date3 ) {
return true;
} else {
return false;
}
}
function filter_woocommerce_available_payment_gateways( $payment_gateways ) {
// Not on admin
if ( is_admin() ) return $payment_gateways;
// Only on custom hour range (call function)
if ( the_time_range() ) {
// Add the payment methods you want to disable, several can be entered, separated by a comma
$disable_payment_gateways = array( 'cod', 'bacs' );
// Loop through
foreach ( $disable_payment_gateways as $disable_payment_gateway ) {
// When the payment method actually exists
if ( isset( $payment_gateways[$disable_payment_gateway] ) ) {
// Unset
unset( $payment_gateways[$disable_payment_gateway] );
}
}
}
return $payment_gateways;
}
add_filter( 'woocommerce_available_payment_gateways', 'filter_woocommerce_available_payment_gateways', 10, 1 );