K
K
Konstantin Lavrovsky2019-12-07 13:56:08
WordPress
Konstantin Lavrovsky, 2019-12-07 13:56:08

How to make it possible to buy only one product?

Good afternoon, I was looking for a code in the public domain that allows only one product to be added to the cart, but they all do not work, here is one of the many that I tried:

add_filter( 'woocommerce_add_to_cart_validation', 'custom_only_one_in_cart', 99, 2 );
function custom_only_one_in_cart( $passed, $added_product_id ) {

    // empty cart first: new item will replace previous
    wc_empty_cart();

    // display a message if you like
    wc_add_notice( 'Max number of items in cart reached!', 'notice' );

    return $passed;
}

This is possible due to the fact that I am adding a product with one click on the button through ajax processing, you probably know this code.
Tell me, please, how to solve this problem?
Maybe there is an opportunity through js to somehow track if there is a product in the basket and if it is, just redirect to checkout?
ajax button handling
$('.s1_oneclick_btn').click(function(e) {
  e.preventDefault();
  $(this).addClass('adding-cart');
  var product_id = '14';

  var ajax_url = "/wp-admin/admin-ajax.php"

  $.ajax ({
    url: ajax_url,  
    type:'POST',
    data:'action=oneclick&product_id=' + product_id + '&quantity=1',
  })
  .done(function() {
    var url = "http://a0368503.xsph.ru/checkout/";
    $(location).attr('href',url);
    });
  });

And the final one in functions.php is adding a product to the cart:
function oneclick() {
  $product_id = $_POST['product_id'];
  $variation_id = $_POST['variation_id'];
  $quantity = $_POST['quantity'];

  if ($variation_id) {
    WC()->cart->add_to_cart( $product_id, $quantity, $variation_id );
  } else {
    WC()->cart->add_to_cart( $product_id, $quantity);
  }

  $items = WC()->cart->get_cart();
  global $woocommerce;
  $item_count = $woocommerce->cart->cart_contents_count; 

  die();
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
T
tuxfighter, 2019-12-07
@s1mypj

in product settings. "Orders" section, "sell individually" checkbox

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question