te')); return $arr; } /* 遍历用户所有主题 * @param $uid 用户ID * @param int $page 页数 * @param int $pagesize 每页记录条数 * @param bool $desc 排序方式 TRUE降序 FALSE升序 * @param string $key 返回的数组用那一列的值作为 key * @param array $col 查询哪些列 */ function thread_tid_find_by_uid($uid, $page = 1, $pagesize = 1000, $desc = TRUE, $key = 'tid', $col = array()) { if (empty($uid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('uid' => $uid), array('tid' => $orderby), $page, $pagesize, $key, $col); return $arr; } // 遍历栏目下tid 支持数组 $fid = array(1,2,3) function thread_tid_find_by_fid($fid, $page = 1, $pagesize = 1000, $desc = TRUE) { if (empty($fid)) return array(); $orderby = TRUE == $desc ? -1 : 1; $arr = thread_tid__find($cond = array('fid' => $fid), array('tid' => $orderby), $page, $pagesize, 'tid', array('tid', 'verify_date')); return $arr; } function thread_tid_delete($tid) { if (empty($tid)) return FALSE; $r = thread_tid__delete(array('tid' => $tid)); return $r; } function thread_tid_count() { $n = thread_tid__count(); return $n; } // 统计用户主题数 大数量下严谨使用非主键统计 function thread_uid_count($uid) { $n = thread_tid__count(array('uid' => $uid)); return $n; } // 统计栏目主题数 大数量下严谨使用非主键统计 function thread_fid_count($fid) { $n = thread_tid__count(array('fid' => $fid)); return $n; } ?>javascript - Get selected variation price in jQuery on Woocommerce Variable products - Stack Overflow
最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get selected variation price in jQuery on Woocommerce Variable products - Stack Overflow

programmeradmin3浏览0评论

How do I use the variation id to find the variations price using javascript? This is what I've got so far. I've got the variations ID, but i can't figure it out. I've been googling it for hours.

add_action( 'woomerce_before_add_to_cart_quantity', 'func_option_valgt' );
function func_option_valgt() {

    global $product;
    global $woomerce;

    if ( $product->is_type('variable') ) {

        ?>
        <script>
        jQuery(document).ready(function($) {

            $('input').change( function(){
                if( '' != $('input.variation_id').val() ) {

                    var var_id = $('input.variation_id').val();

                    var var_length = $('#cfwc-title-field').val(); //LENGTH

                    var var_diameter =$('#diameter').val();  //DIAMETER

                    alert('Du valgte variant #' + var_id + "    Lengde: " + var_length + "     Diameter: " + var_diameter + "    Variantpris: " + var_variant_pris);    
                }
            });
        });
        </script>
        <?php
    }
}

Any help appreciated.

How do I use the variation id to find the variations price using javascript? This is what I've got so far. I've got the variations ID, but i can't figure it out. I've been googling it for hours.

add_action( 'woomerce_before_add_to_cart_quantity', 'func_option_valgt' );
function func_option_valgt() {

    global $product;
    global $woomerce;

    if ( $product->is_type('variable') ) {

        ?>
        <script>
        jQuery(document).ready(function($) {

            $('input').change( function(){
                if( '' != $('input.variation_id').val() ) {

                    var var_id = $('input.variation_id').val();

                    var var_length = $('#cfwc-title-field').val(); //LENGTH

                    var var_diameter =$('#diameter').val();  //DIAMETER

                    alert('Du valgte variant #' + var_id + "    Lengde: " + var_length + "     Diameter: " + var_diameter + "    Variantpris: " + var_variant_pris);    
                }
            });
        });
        </script>
        <?php
    }
}

Any help appreciated.

Share Improve this question edited Oct 1, 2024 at 6:27 LoicTheAztec 254k24 gold badges396 silver badges443 bronze badges asked Feb 28, 2019 at 13:05 PaudunPaudun 2871 gold badge7 silver badges15 bronze badges 3
  • I guess you need this: woomerce.github.io/woomerce-rest-api-docs/#introduction then make an AJAX/fetch call for the info you need. – user5734311 Commented Feb 28, 2019 at 13:18
  • I see there is an attribute called 'price' associated with product variants in the link you provided. Isn't it possible to just write something like var variation_price = $('variation_id.price').val(); or something? – Paudun Commented Feb 28, 2019 at 14:15
  • 1 Ajax is not required for that… You just need to pass the array of variation Id / Price pairs to jQuery, to get the selected variation price. check it in the answer below – LoicTheAztec Commented Feb 28, 2019 at 15:17
Add a ment  | 

3 Answers 3

Reset to default 10

With the following revisited code you will get in your jQuery script the price from the variation ID:

add_action( 'woomerce_before_add_to_cart_quantity', 'func_option_valgt' );
function func_option_valgt() {
    global $product;

    if ( $product->is_type('variable') ) {
        $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
                        length   = $('#cfwc-title-field').val(), // LENGTH
                        diameter = $('#diameter').val(),  // DIAMETER
                        vprice   = ''; // Initilizing

                    // Loop through variation IDs / Prices pairs
                    $.each( jsonData, function( index, price ) {
                        if( index == $(inputVID).val() ) {
                            vprice = price; // The right variation price
                        }
                    });

                    alert('variation Id: '+vid+' | Lengde: '+length+' | Diameter: '+diameter+' | Variantpris: '+vprice);
                }
            });
        });
        </script>
        <?php
    }
}

Code goes on function.php file of your active child theme (or active theme). Tested and works.

Updated code to update the class showing the select var price..

add_action( 'woomerce_before_add_to_cart_quantity', 'func_option_valgt' );
function func_option_valgt() {
    global $product;

    if ( $product->is_type('variable') ) {
        $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
                        length   = $('#cfwc-title-field').val(), // LENGTH
                        diameter = $('#diameter').val(),  // DIAMETER
                        vprice   = ''; // Initilizing

                    // Loop through variation IDs / Prices pairs
                    $.each( jsonData, function( index, price ) {
                        if( index == $(inputVID).val() ) {
                            vprice = price; // The right variation price
                        }
                    });

                    //alert('variation Id: '+vid+' | Lengde: '+length+' | Diameter: '+diameter+' | Variantpris: '+vprice);
                    // Update the need class to show price
                    var csymbol = '&pound;'
                    // SET YOUR CURRANCY SYMBOL ABOVE
                    $(".availability").html(csymbol+vprice);
                }
            });
        });
        </script>
        <?php
    }
}

Get selected variation price on select change

In my case I need to get the price when the user select on one of the options from the select HTML tag.

add_action( 'woomerce_before_add_to_cart_quantity', 'get_price_on_select_change' );
function get_price_on_select_change() {
    global $product;

    if ( $product->is_type('variable') ) {
        $variations_data =[]; // Initializing

        // Loop through variations data
        foreach($product->get_available_variations() as $variation ) {
            $variations_data[$variation['variation_id']] = $variation['display_price'];
        } 
        ?>
      <script>
        const jsonData = <?php echo json_encode($variations_data);?> 
        document.addEventListener('DOMContentLoaded', () => {
        const selectedVariationId = document.querySelector('.variation_id')
        const select = document.querySelector('#pa_pack-size');
        select.addEventListener('change', () => {
           setTimeout(() => {
             alert(jsonData[selectedVariationId.value])
          },50)
        })
        })
      </script>
        <?php
    }
}

The setTimeout function is to add a short delay, just enough time to update the .variation_id input value.

Tested and it works!

PS: Thank you @LoicTheAztec for the idea!

发布评论

评论列表(0)

  1. 暂无评论