我有一个 WordPress 网站: 如果购物车中只有这些产品,我想为属性
snapppay
具有 3ml
、5ml
或 10ml
值的可变产品禁用其中一种付款方式 (vol
)。
例如,应允许我的客户购买任意数量具有 3ml
、5ml
或 10ml
值的产品,其中至少一种产品具有任何不同的 vol
(不是 3、5 或 10 毫升)
我尝试了这段代码,但我的网站停止工作:
function modify_available_payment_gateways($gateways) {
$flag = false;
$cart = WC()->cart;
$cart_num = count($cart->get_cart());
$dec_num = 0;
// Loop through cart items
foreach( $cart->get_cart() as $cart_item ) {
if( $cart_item['variation_id'] > 0 ){
// Loop through product attributes values set for the variation
foreach( $cart_item['variation'] as $term_slug ){
// comparing attribute term value with current attribute value
if ($term_slug === '3ml' || $term_slug === '5ml' || $term_slug === '10ml') {
$dec_num = $dec_num + 1;
}
}
}
if ($cart_num === $dec_num){
$flag = true;
}
}
// When the flag is true
if ( $flag) {
// Clear all other notices
wc_clear_notices();
// Avoid checkout displaying an error notice
wc_add_notice( __( 'My Error Message.', 'woocommerce' ), 'error' );
// Optional: remove the payment method you want to hide
unset($gateways['snapppay']);
}
return $gateways;
}
add_filter('woocommerce_available_payment_gateways', 'modify_available_payment_gateways');
为了避免这个问题,你首先需要只针对结帐,并且你的代码也可以简化。
尝试以下操作:
add_filter('woocommerce_available_payment_gateways', 'modify_available_payment_gateways');
function modify_available_payment_gateways( $available_gateways ) {
if ( is_checkout() && ! is_wc_endpoint_url() && isset($available_gateways['snapppay']) ) {
// Loop through cart items
foreach( WC()->cart->get_cart() as $cart_item ) {
if( $cart_item['variation_id'] > 0 ){
// Loop through product attributes values set for the variation
foreach( $cart_item['variation'] as $term_slug ){
// comparing attribute term value with current attribute value
if ( ! in_array($term_slug, ['3ml', '5ml', '10ml']) ) {
return $available_gateways;
}
}
} else {
return $available_gateways;
}
}
unset($available_gateways['snapppay']);
}
return $available_gateways;
}
代码位于子主题的functions.php 文件中(或插件中)。应该可以。