web-dev-qa-db-fra.com

Besoin de Woocommerce pour autoriser uniquement 1 produit dans le panier. Si un produit est déjà dans le panier et qu'un autre 1 est ajouté, il doit supprimer le précédent 1

Je pense que ce code devrait fonctionner mais pas exactement où le placer. Partout où j'ai essayé a échoué jusqu'à présent ...

add_action('init', 'woocommerce_clear_cart');

function woocommerce_clear_cart() {
global $woocommerce, $post, $wpdb;

$url = explode('/', 'http://'.$_SERVER["HTTP_Host"] . $_SERVER["REQUEST_URI"]);
$slug=$url[4];
$postid = $wpdb->get_var("SELECT ID FROM $wpdb->posts WHERE post_status='publish' AND post_name = '$slug'");

    if ($postid){
        if ($postid == PRODUCTID1 || $postid == PRODUCTID2){
        $woocommerce->cart->empty_cart();
        }
    }

}
18
Swof

Malheureusement, il n'y a pas de crochet d'action avant que WooCommerce ajoute un article au panier. Mais ils ont un crochet "filtre" avant de l'ajouter au panier. Voilà comment je l'utilise:

add_filter( 'woocommerce_add_cart_item_data', 'woo_custom_add_to_cart' );

function woo_custom_add_to_cart( $cart_item_data ) {

    global $woocommerce;
    $woocommerce->cart->empty_cart();

    // Do nothing with the data and return
    return $cart_item_data;
}
38
fornyhucker

Sur la base de la réponse acceptée et de la dernière version 2.5.1 de Woo, j'ai mis à jour la fonction pour être légèrement plus propre en utilisant le code utilisé par woo dans class-wc-checkout.php pour vider le panier

add_filter( 'woocommerce_add_cart_item_data', '_empty_cart' );

    function _empty_cart( $cart_item_data ) {

        WC()->cart->empty_cart();

        return $cart_item_data;
    }
14
Jared

De mon réponse à une autre question :

Il y a un filtre/crochet qui s'exécute avant qu'un article soit ajouté au panier pendant que chaque produit passe par la validation avant d'être ajouté.

Ainsi, lors de la validation d'un produit, nous pouvons vérifier si l'article s'il y a déjà des articles dans le panier et les effacer (si l'article actuel peut être ajouté) et ajoute un message d'erreur.

/**
 * When an item is added to the cart, remove other products
 */
function so_27030769_maybe_empty_cart( $valid, $product_id, $quantity ) {

    if( ! empty ( WC()->cart->get_cart() ) && $valid ){
        WC()->cart->empty_cart();
        wc_add_notice( 'Whoa hold up. You can only have 1 item in your cart', 'error' );
    }

    return $valid;

}
add_filter( 'woocommerce_add_to_cart_validation', 'so_27030769_maybe_empty_cart', 10, 3 );
10
helgatheviking

Cela a fonctionné comme un charme pour moi, supprime le produit précédent et ajoute le nouveau avec la nouvelle configuration du produit. À votre santé

Mise à jour: pour WooCommerce 3.0.X

function check_if_cart_has_product( $valid, $product_id, $quantity ) {  

            if(!empty(WC()->cart->get_cart()) && $valid){
                foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
                    $_product = $values['data'];

                    if( $product_id == $_product->get_id() ) {
                        unset(WC()->cart->cart_contents[$cart_item_key]);
                    }
                }
            }

            return $valid;

        }
        add_filter( 'woocommerce_add_to_cart_validation', 'check_if_cart_has_product', 10, 3 );

Pour la version WooCommerce inférieure à 3.0.X

function check_if_cart_has_product( $valid, $product_id, $quantity ) {  

    if(!empty(WC()->cart->get_cart()) && $valid){
        foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
            $_product = $values['data'];

            if( $product_id == $_product->id ) {
                unset(WC()->cart->cart_contents[$cart_item_key]);
            }
        }
    }

    return $valid;

}
add_filter( 'woocommerce_add_to_cart_validation', 'check_if_cart_has_product', 10, 3 );
5
Digamber

Vous avez deux options:

  1. extension WooCommerce Quantités Min/Max
  2. Le code suivant ajouté à votre functions.php fichier de thème
 
 add_filter ('woocommerce_before_cart', 'allow_single_quantity_in_cart'); 
 fonction allow_single_quantity_in_cart () {
 global $ woocommerce; 
 
 $ cart_contents = $ woocommerce-> cart-> get_cart (); 
 $ keys = array_keys ($ cart_contents); 
 
 foreach ($ keys as $ key) {
 $ woocommerce-> cart-> set_quantity ($ key, 1, true); 
} 
} 
 
4

N'ajoutez pas de fonctions directement à vos fichiers de commerce ... vous perdrez tout votre code lors de la mise à jour.

Les fonctions utilisateur doivent toujours être accrochées via le fichier functions.php de votre thème.

3
Ross

Si vous souhaitez limiter le nombre de produits à seulement 1:

function check_if_cart_has_product( $valid, $product_id, $quantity ) {  

    if(!empty(WC()->cart->get_cart()) && $valid){
        foreach (WC()->cart->get_cart() as $cart_item_key => $values) {
            $_product = $values['data'];

            if( $product_id == $_product->id ) {
                wc_add_notice( 'The product is already in cart', 'error' );
                return false;
            }
        }
    }

    return $valid;

}
add_filter( 'woocommerce_add_to_cart_validation', 'check_if_cart_has_product', 10, 3 );
2
Rao

Essaye ça,

Pour retirer tous les produits du panier et ajouter le dernier ajouté,

//For removing all the items from the cart
global $woocommerce;
$woocommerce->cart->empty_cart();
$woocommerce->cart->add_to_cart($product_id,$qty);

le fichier de classe est wp-content/plugins/woocommerce/classes/class-wc-cart.php.

Vous pouvez ajouter le code ci-dessus sur la fonction d'ajout au panier dans functions.php.

J'espère que ses œuvres ..

2
Jobin Jose