首页 > 解决方案 > Woocommerce中基于嵌套IF语句中的多个数组的条件

问题描述

基本上,如果满足第一个语句的标准,我试图让第二个IF语句起作用If

第一条IF语句用于检查用户角色,如果它与“bba”或“duk”匹配,那么第二条IF语句将检查不应匹配的特定产品 ID,从而避免自定义购物车范围的批量折扣。

我知道第二个IF语句可以自行工作,但它会禁用所有用户的批量折扣,而不是特定定义的用户。

这是我的代码:

if ( in_array( 'bba', 'duk' (array) $user->roles ) ) {

    if( ! in_array($values['product_id'], array('493','387'))){
      $quantiy_total += $values['quantity'];  
      //$price = get_post_meta($values['product_id'] , '_price', true);

      $price = $values['line_subtotal'];

     // echo "####".$price."####";


      $cart_total += $price;
    }   

  }
  }

或者我的第二次尝试也不起作用:

if ( ! in_array($user['roles'], array('bba','duk'))){

    if( ! in_array($values['product_id'], array('493','387'))){
      $quantiy_total += $values['quantity'];  
      //$price = get_post_meta($values['product_id'] , '_price', true);

      $price = $values['line_subtotal'];

     // echo "####".$price."####";


      $cart_total += $price;
    }   

  }
  }

使用这两个代码,产品 ID 439 和 387 的批量折扣将被禁用,而不考虑 FirstIF语句。

如何使第一个IF语句工作并检查目标用户角色?

任何帮助表示赞赏。

标签: phparrayswordpressif-statementwoocommerce

解决方案


在您第一个IF使用 2 个数组时,您需要使用array_intersect()而不是in_array().

还有一些其他的错误。尝试以下操作:

$cart = WC()->cart; // (If needed) The cart object

$total_quantity = $total_amount = 0; // Initializing variables

if ( array_intersect( array('bba','duk'),  $user['roles'] ) ) {
    // Loop through cart items
    foreach( $cart-get_cart() as $cart_item )
        if ( ! in_array( $cart_item['data']->get_id(), array('493','387') ) ) {
            // Cumulated total quantity of targeted cart items
            $total_quantity += $cart_item['quantity'];

            // The product price
            // $price = $cart_item['data']->get_price();

            // The line item subtotal not discounted (product price x quantity)
            $subtotal_price = $cart_item['line_subtotal'];

            // The line item total discounted ( (product price x quantity) - coupon discount )
            // $total_price = $cart_item['line_total'];

            // Cumulated line subtotals amount of targeted cart items
            $subtotal_amount += $subtotal_price;
        }
    }
}

// Testing output
echo '<p>Total quantity is ' . $total_quantity . ' and Subtotal amount is ' . $subtotal_amount . '</p>';

它现在应该更好地工作。


推荐阅读