wordpress 在woocommerce中禁用具有特定属性值的可变产品的特定支付方法

jxct1oxe  于 2023-11-17  发布在  WordPress
关注(0)|答案(1)|浏览(121)

我有一个WordPress网站:我想禁用其中一种付款方式(snapppay)对于属性vol具有3ml5ml10ml值的可变产品,如果只有这些产品在购物车中。例如,我的客户应该被允许任意数量的具有3ml5ml、或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');

字符串

lkaoscv7

lkaoscv71#

为了避免这个问题,你首先需要只针对 checkout ,并且你的代码可以被简化。
尝试以下操作:

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文件中(或者插件中)。它应该可以工作。

相关问题