dallynX

Изменение цены вариативного товара

Nov 30th, 2019
203
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.27 KB | None | 0 0
  1. add_action( 'woocommerce_after_single_product_summary', 'add_custom_script', 5 );
  2.  
  3. function add_custom_script(){
  4.  
  5.   global $product;
  6.  
  7.   if( $product->get_type() === 'variable' ){
  8. ?>
  9. <script type="text/javascript">
  10. // === 171 ===
  11.  
  12.  
  13. dlnAdjust();
  14.  
  15.  
  16. function dlnAdjust(){
  17.   let entrySummary = document.querySelector( '.summary.entry-summary' );
  18.   let price = entrySummary.querySelector( 'p.price' );
  19.   let form = entrySummary.querySelector( 'form' );
  20.   let html = price.innerHTML;
  21.   html = '<span class="box-for-range-price">' + html + '</span><span class="box-for-single-price"></span>';
  22.   price.innerHTML = html;
  23.   let rangeBox = price.querySelector( '.box-for-range-price' );
  24.   let singleBox = price.querySelector( '.box-for-single-price' );
  25.   let singleVar = entrySummary.querySelector( '.woocommerce-variation.single_variation' );
  26.   html = singleVar.outerHTML;
  27.   html = '<div class="box-for-single-variation" style="display: none;">' + html + '</div>';
  28.   singleVar.outerHTML = html;
  29.   form.addEventListener( 'change', formChange );
  30.   formChange();
  31.  
  32.  
  33. function formChange(){
  34.   let chooseSel = fChooseSel();
  35.   let variations = form.getAttribute( 'data-product_variations' );
  36.   variations = eval( variations );
  37.   let chosenVar = fChosenVar( chooseSel, variations );
  38.   if( chosenVar !== undefined ){
  39.     let html = chosenVar[ 'price_html' ];
  40.     rangeBox.style.display = 'none';
  41.     singleBox.innerHTML = html; }
  42.   else{
  43.     singleBox.innerHTML = '';
  44.     rangeBox.style.display = 'inline'; }
  45. } // formChange  
  46.  
  47.  
  48. function fChooseSel(){
  49.   let selects = form.querySelectorAll( 'select' );
  50.   let choose = [];
  51.   selects.forEach( function ( for_select ){
  52.     let name = for_select.getAttribute( 'data-attribute_name' );
  53.     let vValue = for_select.value;
  54.     let elem = { 'name': name, 'value': vValue }
  55.     choose.push( elem );
  56.   });
  57.   return choose;
  58. }
  59.  
  60.  
  61. function fChosenVar( chooseSel, variations ){
  62.   for( let forVar of variations ){
  63.     let attributes = forVar[ 'attributes' ];
  64.     let check = true;
  65.     for( let forSel of chooseSel ){
  66.       let name = forSel[ 'name' ]; let vValue = forSel[ 'value' ];
  67.       if( attributes[ name ] != vValue){ check = false; break; }}
  68.     if( check ){ return forVar; }}  
  69. }
  70.  
  71. }  // dlnAdjust
  72. </script>
  73. <?php
  74.   }
  75. }
Add Comment
Please, Sign In to add comment