如果 Woocommerce 已经在购物车中,则禁用产品变体

时间:2021-01-20 11:18:17

标签: php wordpress woocommerce

我创建了一个小脚本,试图排除已在购物车中可供购买的产品变体上的 WC 产品变体。

如果购物车中有 1 个变体,则以下脚本将起作用,从而在产品页面上禁用该变体。但是,当在购物车中添加更多变体时,这些时间段仍然是可能的。有人看到我在这里缺少什么吗?

脚本思路:所有WC产品具有相同的变化可能性(时间段+天)

  1. 获取当前用户购物车中所有产品的变体
  2. 获取当前产品的产品变体,除了购物车中的变体组合
  3. 显示用户可以选择的剩余变化,不能与购物车中的时间段重叠
// 1st part - get current variations from products_in_cart() {
  $products_in_cart = array();
  $cart_items =  WC()->cart->get_cart();
  //
  foreach( $cart_items as $cart_item ){
    if ($cart_item['product_id']) {
      //$products_in_cart[] = $cart_item['variation_id'];
      //$products_in_cart[] = $cart_item['variation'];
      $exclude = implode(' ', $cart_item['variation']);
      echo '<font color="red">Combi in cart: ' . $exclude . '</font><br/>';
    }
  }

  if (count($products_in_cart) > 0) {}
//print_r ($products_in_cart);

// 2nd part of the script; comparing variations in cart to current product view variations
 //function woocommerce_variable_add_to_cart() {
 global $product, $post;
 $variations = $product->get_available_variations();
 ?>
 <table>
    <tbody>
    <?php 
    foreach ($variations as $key => $value) {
    $possibleoption = implode(' ', $value['attributes']);
    //if(!empty($value['attributes'])){
    if(!empty($value['attributes']) AND ($possibleoption != $exclude)){
    ?>
    <tr>
        <td>
            <b>
            <?php
            echo $possibleoption;
            ?>
            </b>
        </td>
        <td>
          
            <form action="<?php echo esc_url( $product->add_to_cart_url() ); ?>" method="post" enctype='multipart/form-data'>
            <input type="hidden" name="variation_id" value="<?php echo $value['variation_id']?>" />
            <input type="hidden" name="product_id" value="<?php echo esc_attr( $post->ID ); ?>" />
            <input type="hidden" name="add-to-cart" value="<?php echo esc_attr( $post->ID ); ?>" />
            <?php
            if(!empty($value['attributes'])){
            foreach ($value['attributes'] as $attr_key => $attr_value) {
                ?>
                <input type="hidden" name="<?php echo $attr_key?>" value="<?php echo $attr_value?>">
                <?php
                }
            }
            ?>
            <button type="submit" class="single_add_to_cart_button button alt"><?php echo apply_filters('single_add_to_cart_text', __( 'Add to cart', 'woocommerce' ), $product->product_type); ?></button>
            </form>
 
        </td>
        <td>
            <b>
            <?php echo $value['price_html'];?>
            </b>
        </td>
    </tr>
    <?php
    }
    }
    ?>
    </tbody>
 </table>
<?php
 //}

实时脚本(选择一个并添加到购物车,仅使用按钮): https://app.sportenbewegenhilversum.nl/product-categorie/keuzedelen/

Image explaining frontend situation

0 个答案:

没有答案