Woocommerce - Restrict user to add products into cart with particular combination

In Woocommerce if we need to Restrict user to add products  into cart  with  particular combination, we have to follow few steps.

<?php

// Step1: 

function aelia_get_cart_contents() {
  $cart_contents = array();
  $cart = WC()->session->get( 'cart', null );
   if ( is_null( $cart ) && ( $saved_cart = get_user_meta( get_current_user_id(), '_woocommerce_persistent_cart', true ) ) ) {
    $cart = $saved_cart['cart'];
  } elseif ( is_null( $cart ) ) {
    $cart = array();
  }

  if ( is_array( $cart ) ) {
    foreach ( $cart as $key => $values ) {
      $_product = wc_get_product( $values['variation_id'] ? $values['variation_id'] : $values['product_id'] );

      if ( ! empty( $_product ) && $_product->exists() && $values['quantity'] > 0 ) {
        if ( $_product->is_purchasable() ) {
         $session_data = array_merge( $values, array( 'data' => $_product ) );
          $cart_contents[ $key ] = apply_filters( 'woocommerce_get_cart_item_from_session', $session_data, $values, $key );
        }
      }
    }
  }
  return $cart_contents;
}

// Step2:

add_action('wp_loaded', function() {
    if(!is_object(WC()->session)) {
    return;
  }

  global $allowed_cart_items;
  // I am adding products with ID 5395,5138,5046,5137,5134,5133,5131 as a combination.
  global $restricted_cart_items;
  $restricted_cart_items = array(5395,5138,5046,5137,5134,5133,5131);

  foreach(aelia_get_cart_contents() as $item) {
    if(in_array($item['data']->id, $restricted_cart_items)) {
      $allowed_cart_items[] = $item['data']->id;
    }
  }

  // Step3:

  add_filter('woocommerce_is_purchasable', function($is_purchasable, $product) {
    global $restricted_cart_items;
    global $allowed_cart_items;

    if(!empty($allowed_cart_items)) {
           $is_purchasable = in_array($product->id, $allowed_cart_items) || in_array($product->id, $restricted_cart_items);
    }
    return $is_purchasable;
  }, 10, 2);
}, 10);

// Step4

add_filter('woocommerce_get_price_html', function($price_html, $product) {
  if(!$product->is_purchasable() && is_product()) {
    $price_html .= '<p>' . __('<h3 style="font-weight:bold;">This product cannot be added to cart  with the combination of  <span style="color:#d06569">Product / Category Name</span>. Remove other items from cart and try purchasing it.</h3>', 'woocommerce') . '</p>';
  }
  return $price_html;
}, 10, 2);

// Step5

// Done!!
?>

No comments:

Post a Comment