Partage
  • Partager sur Facebook
  • Partager sur Twitter

WooCommerce - Prix dans bouton add to cart

    13 janvier 2021 à 13:33:27

    Bonjour,

    J'ai un petit soucis, et je n'arrive pas à le résoudre seul. Tout fonctionnait niquel et depuis aujourd'hui (enfin, je crois) je n'arrive pas à faire afficher le prix d'un article en variable dans mon bouton add to cart.
    Pourtant, ça fonctionne avec les produits n'ayant pas de variable.

    Voici un exemple : http://www.jgh-webdesign.fr/HCPRESTIGE/produit/get-ready-micellar-spray/
    On peut y voir que s'affiche bien le symbole "€", mais normalement il devrait y avoir le prix aussi, en fonction du choix des ml.
    Je ne comprends pas pourquoi il ne s'affiche pas, surtout que quand on analyse le script, il a bien récupéré le prix des 2 variations.

    Une idée quelqu'un ?

    Voici le code que j'utilise :

    add_filter( 'woocommerce_product_add_to_cart_text', 'custom_add_to_cart_price', 20, 2 ); // Shop and other archives pages
    add_filter( 'woocommerce_product_single_add_to_cart_text', 'custom_add_to_cart_price', 20, 2 ); // Single product pages
    function custom_add_to_cart_price( $button_text, $product ) {
        // Variable products
        if( $product->is_type('variable') ) {
            // shop and archives
            if( ! is_product() ){
    
                $product_price = wc_price( wc_get_price_to_display( $product, array( 'price' => $product->get_variation_price() ) ) );
                return $button_text . ' - Dès ' . strip_tags( $product_price );
            } 
            // Single product pages
            else {
                $variations_data =[]; // Initializing
    
            // Loop through variations data
            foreach($product->get_available_variations() as $variation ) {
                // Set for each variation ID the corresponding price in the data array (to be used in jQuery)
                $variations_data[$variation['variation_id']] = $variation['display_price'];
            }
            ?>
            <script>
            jQuery(function($) {
                var jsonData = <?php echo json_encode($variations_data); ?>,
                    inputVID = 'input.variation_id';
    
                $('input').change( function(){
                    if( '' != $(inputVID).val() ) {
                        var vid      = $(inputVID).val(), // VARIATION ID
                           vprice   = ''; // Initilizing
    
                        // Loop through variation IDs / Prices pairs
                        $.each( jsonData, function( index, price ) {
                            if( index == $(inputVID).val() ) {
                                vprice = (price).toFixed(2); // The right variation price
                            }
                        });
                        // Change price dynamically when changing options
                        $( "button.single_add_to_cart_button.button.alt span" ).remove();
                        $(".single_add_to_cart_button").append("<span>" + " " + vprice + " €" + "</span>");
                    }
                });
            });
            </script><?php
                return $button_text;
            }
        } 
        // All other product types
        else {
            $product_price = wc_price( wc_get_price_to_display( $product ) );
            return $button_text . '  ' . strip_tags( $product_price );
        }
    }



    • Partager sur Facebook
    • Partager sur Twitter
      14 janvier 2021 à 10:23:10

      Salut,

      Jette un œil à ton code via le debugger. Voilà ce que ça donne en vidéo coté client :

      https://streamable.com/xqimpw

      Tu as une deuxième fois ton code dans la section "PRODUITS APPARENTÉS" (ligne ~1214 dans la console) et ça vient faire le bazar avec le premier exemplaire de ton code...

      Sans doute que ton code n'est pas situé là ou il devrait l'être dans ton fichier php. A moins que tu ais véritablement un doublon.

      -
      Edité par BrainError 14 janvier 2021 à 10:26:21

      • Partager sur Facebook
      • Partager sur Twitter
        15 janvier 2021 à 13:03:15

        Salut BrainError,

        Merci pour le retour !

        Pas de doublon, mon code se trouve dans function.php

        C'est vraiment étrange, mon produits apparentés c'est les produits similaires, je ne comprends pas pourquoi il fait doublon avec :/

        En tout cas on sait maintenant d'où ça vient !

        **EDIT**

        En fait, dès que j'ai un autre display de produit (similaire, vente croisée, ou product grid), ça ne fonctionne plus.

        J'imagine qu'il faudrait donc dire à mon script de ne fonctionner que sur la partie qui m'intéresse, est-ce possible ?

        -
        Edité par JérémyHédin 15 janvier 2021 à 13:26:38

        • Partager sur Facebook
        • Partager sur Twitter
          18 janvier 2021 à 13:26:56

          Personne n'aurait une idée de comment "dire" à mon code de ne fonctionner QUE sur un block spécifique ?

          Le problème c'est que dès que j'ai un autre display de produit (similaire, vente croisée, ou product grid), ça ne fonctionne plus... C'est un peu relou !

          • Partager sur Facebook
          • Partager sur Twitter
            18 janvier 2021 à 15:12:00

            Salut,

            Ben a partir de là, il faut aller jeter un oeil au php de ton wordpress et c'est beaucoup moins marrant.

            Puisque ton code JS ne doit être inclus qu'une seule fois, ma solution pas top propre est la suivante :

            add_filter( 'woocommerce_product_add_to_cart_text', 'custom_add_to_cart_price', 20, 2 ); // Shop and other archives pages
            add_filter( 'woocommerce_product_single_add_to_cart_text', 'custom_add_to_cart_price', 20, 2 ); // Single product pages
            function custom_add_to_cart_price( $button_text, $product ) {
                global $__once;
                // Variable products
                if( $product->is_type('variable')) {
                    // shop and archives
                    if( ! is_product() ){
             
                        $product_price = wc_price( wc_get_price_to_display( $product, array( 'price' => $product->get_variation_price() ) ) );
                        return $button_text . ' - Dès ' . strip_tags( $product_price );
                    }
                    // Single product pages
                    else {
                        $variations_data =[]; // Initializing
             
            			// Loop through variations data
            			foreach($product->get_available_variations() as $variation ) {
            				// Set for each variation ID the corresponding price in the data array (to be used in jQuery)
            				$variations_data[$variation['variation_id']] = $variation['display_price'];
            			}
            			if(!$__once) {
            				$__once = true;
            				?>
            				<script>
            				jQuery(function($) {
            					var jsonData = <?php echo json_encode($variations_data); ?>,
            						inputVID = 'input.variation_id';
            	 
            					$('input').change( function(){
            						if( '' != $(inputVID).val() ) {
            							var vid      = $(inputVID).val(), // VARIATION ID
            							   vprice   = ''; // Initilizing
            	 
            							// Loop through variation IDs / Prices pairs
            							$.each( jsonData, function( index, price ) {
            								if( index == $(inputVID).val() ) {
            									vprice = (price).toFixed(2); // The right variation price
            								}
            							});
            							// Change price dynamically when changing options
            							$( "button.single_add_to_cart_button.button.alt span" ).remove();
            							$(".single_add_to_cart_button").append("<span>" + " " + vprice + " €" + "</span>");
            						}
            					});
            				});
            				</script><?php
            			}
                        return $button_text;
                    }
                }
                // All other product types
                else {
                    $product_price = wc_price( wc_get_price_to_display( $product ) );
                    return $button_text . '  ' . strip_tags( $product_price );
                }
            }
            • 1) (Ligne 4) Tu récupère la valeur d'une variable $__once définie globalement.
            • 2) (Ligne 22, 23 & 48) Si la valeur de cette variable n'est pas définie, alors tu la définie sur true et ajoutes ton block de script.
            • 3) Sinon, tu ne fais rien.

            Je suis pas un spécialiste de Wordpress ni même bon en PHP. Je ne peux donc pas garantir que mon exemple fonctionne. A toi d'essayer de trouver la solution à partir de ce principe ou d'un principe similaire.

            -
            Edité par BrainError 18 janvier 2021 à 15:14:19

            • Partager sur Facebook
            • Partager sur Twitter
              20 janvier 2021 à 13:13:10

              Oh mec je t'aime tellement si tu savais !
              Ton code fonctionne, j'en ai compris le principe avec ton explication et ça me semble parfait. J'ai remplacé mon code par le tiens, ajouté à nouveau les autres displays produits et paf ! Tout ce passe comme il se doit c'est super !


              BrainError a écrit:

              Salut,

              Ben a partir de là, il faut aller jeter un oeil au php de ton wordpress et c'est beaucoup moins marrant.

              Puisque ton code JS ne doit être inclus qu'une seule fois, ma solution pas top propre est la suivante :

              add_filter( 'woocommerce_product_add_to_cart_text', 'custom_add_to_cart_price', 20, 2 ); // Shop and other archives pages
              add_filter( 'woocommerce_product_single_add_to_cart_text', 'custom_add_to_cart_price', 20, 2 ); // Single product pages
              function custom_add_to_cart_price( $button_text, $product ) {
                  global $__once;
                  // Variable products
                  if( $product->is_type('variable')) {
                      // shop and archives
                      if( ! is_product() ){
               
                          $product_price = wc_price( wc_get_price_to_display( $product, array( 'price' => $product->get_variation_price() ) ) );
                          return $button_text . ' - Dès ' . strip_tags( $product_price );
                      }
                      // Single product pages
                      else {
                          $variations_data =[]; // Initializing
               
              			// Loop through variations data
              			foreach($product->get_available_variations() as $variation ) {
              				// Set for each variation ID the corresponding price in the data array (to be used in jQuery)
              				$variations_data[$variation['variation_id']] = $variation['display_price'];
              			}
              			if(!$__once) {
              				$__once = true;
              				?>
              				<script>
              				jQuery(function($) {
              					var jsonData = <?php echo json_encode($variations_data); ?>,
              						inputVID = 'input.variation_id';
              	 
              					$('input').change( function(){
              						if( '' != $(inputVID).val() ) {
              							var vid      = $(inputVID).val(), // VARIATION ID
              							   vprice   = ''; // Initilizing
              	 
              							// Loop through variation IDs / Prices pairs
              							$.each( jsonData, function( index, price ) {
              								if( index == $(inputVID).val() ) {
              									vprice = (price).toFixed(2); // The right variation price
              								}
              							});
              							// Change price dynamically when changing options
              							$( "button.single_add_to_cart_button.button.alt span" ).remove();
              							$(".single_add_to_cart_button").append("<span>" + " " + vprice + " €" + "</span>");
              						}
              					});
              				});
              				</script><?php
              			}
                          return $button_text;
                      }
                  }
                  // All other product types
                  else {
                      $product_price = wc_price( wc_get_price_to_display( $product ) );
                      return $button_text . '  ' . strip_tags( $product_price );
                  }
              }
              • 1) (Ligne 4) Tu récupère la valeur d'une variable $__once définie globalement.
              • 2) (Ligne 22, 23 & 48) Si la valeur de cette variable n'est pas définie, alors tu la définie sur true et ajoutes ton block de script.
              • 3) Sinon, tu ne fais rien.

              Je suis pas un spécialiste de Wordpress ni même bon en PHP. Je ne peux donc pas garantir que mon exemple fonctionne. A toi d'essayer de trouver la solution à partir de ce principe ou d'un principe similaire.

              -
              Edité par BrainError 18 janvier 2021 à 15:14:19



              -
              Edité par JérémyHédin 20 janvier 2021 à 13:13:27

              • Partager sur Facebook
              • Partager sur Twitter

              WooCommerce - Prix dans bouton add to cart

              × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
              × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
              • Editeur
              • Markdown