WooCommerce

Incrémenter le prix en fonction de la quantité d’un produit

Josselyn Jayant
4 octobre 2023
Lecture : 1 min

Le code permet d’afficher un montant total qui affiche le prix par unité multiplié par la quantité que le client va sélectionner.
Cela fonctionne si c’est un produit variable ou un produit simple !

				
					/******************************************************/
/* Afficher le prix en fonction de la quantité produit */
/******************************************************/
function action_woocommerce_before_add_to_cart_button() {
    global $product;

    $currency = get_woocommerce_currency_symbol();

    // Initialisez le sous-total pour les produits simples
    $initialSubtotal = $product->is_type('simple') ? ('Total: ' . $product->get_price() . $currency) : '';
    
    echo '<div id="subtotal" style="'. ($product->is_type('simple') ? '' : 'display:none;') .'"><span>' . $initialSubtotal . '</span></div>';
    
    wc_enqueue_js( "      
        var currentPrice = " . ($product->is_type('simple') ? $product->get_price() : 0) . ";

        // Si c'est un produit variable
        if ( $('.variations_form').length ) {
            $(document).on('found_variation', '.variations_form', function(event, variation) {
                currentPrice = variation.display_price;
                updateSubtotal();
                $('#subtotal').show();
            });

            $(document).on('reset_data', '.variations_form', function() {
                $('#subtotal').hide();
            });
        }

        $( '[name=quantity]' ).on( 'input change', function() {
            updateSubtotal();
        }).change();

        function updateSubtotal() {
            var qty = $( '[name=quantity]' ).val();
            var price_string = ( currentPrice * qty ).toFixed(2);
            
            if ( qty >= 1 ) {
                $( '#subtotal > span').html( 'Total: ' + price_string + \"" . esc_js( $currency ) . "\" );
            } else {
                $( '#subtotal > span').html( '' );                
            }
        }
    " );
}
add_action( 'woocommerce_after_add_to_cart_form', 'action_woocommerce_before_add_to_cart_button', 10, 0 );
				
			
Avant de commencer

Faites une sauvegarde de votre site avant toute modification de code, et testez d’abord sur une copie de travail.

Besoin d’aide pour l’intégrer ?

Je m’en occupe, ou je l’adapte à votre boutique.

À lire aussi

Elementor · Extensions

Bouton retour en haut pour Elementor

Elementor · Extensions · WooCommerce

Elementor : afficher le stock d’un produit WooCommerce dans un widget

Elementor

Menu sticky intelligent (hide on scroll)