首页 > 解决方案 > PHP - 特定的 if/or 语句

问题描述

当使用特定促销代码时,我在我的 WooCommerce 商店的 functions.php 中使用以下代码在结帐时添加费用

function conditional_custom_fee( $cart ) {
    if ( is_admin() && ! defined( 'DOING_AJAX' ) )
        return;

    // HERE set your targeted coupon code
    $coupon_code = 'ABC123' ;

    // Check if our targeted coupon is applied
    if( in_array( wc_format_coupon_code( $coupon_code ), $cart->get_applied_coupons() ) ){
        $title = __('One-off fee', 'woocommerce'); // The fee title
        $cost  = 2.5; // The fee amount

        // Adding the fee (not taxable)
        $cart->add_fee( $title, $cost, false );
    }
}

除了这个之外,我希望能够在其他促销代码上使用此规则。作为 PHP 新手,我将如何更改此代码以便能够使用该代码ABC123,或者XYZ789应用此2.5费用?

标签: phpif-statementwoocommerce

解决方案


如果您只想检查第二个优惠券代码,您可以修改if语句:

if( in_array( wc_format_coupon_code( $coupon_code ), $cart->get_applied_coupons() ) ){

要检查两个不同的条件,请使用||(or) 逻辑运算符。

在此示例中,我们要检查是否使用了优惠券代码ABC123OR YYZ789

if( in_array( wc_format_coupon_code( "ABC123" ), $cart->get_applied_coupons() ) ||
    in_array( wc_format_coupon_code( "XYZ789" ), $cart->get_applied_coupons() ) ){

推荐阅读