WooCommerce: trigger event after change of variation

前端 未结 3 1823
刺人心
刺人心 2020-12-02 10:58

We use Woocommerce to sell colorboxes. Mostly the variable-product option is chosen.

We added a modal dialog with a color palette, where the customer can chose a co

相关标签:
3条回答
  • 2020-12-02 11:25

    In case anyone stumbles across this in the future: WooCommerce provides triggers throughout the add-to-cart-variation.js which allows you to hook into change events for the website. You can find all of them available in that file, but one which will likely help most in this case can be used as such

    $( ".variations_form" ).on( "woocommerce_variation_select_change", function () {
        // Fires whenever variation selects are changed
    } );
    
    $( ".single_variation_wrap" ).on( "show_variation", function ( event, variation ) {
        // Fired when the user selects all the required dropdowns / attributes
        // and a final variation is selected / shown
    } );
    

    Where the trigger you want to hook into is the first argument inside .on(). Here's a few below to get you started:

    woocommerce_variation_select_change Fires when the select is changed.

    show_variation is fired when it finds a variation, and will actually pass you the variation object that is found so you can get direct access to the price without having to filter through the selects manually.

    You can sift through and find the rest here.

    0 讨论(0)
  • 2020-12-02 11:33

    This code performs the exact functionality requested in the initial question:

    $('#WC_variation_drop_down_ID').trigger('change');
    

    Change '#WC_variation_drop_down_ID' to the actual ID of the field you changed with jQuery.

    Here is a more complete solution that includes setting the field as well as triggering the WooCommerce variation selection (based on array of radio button field classes):

    var fields = ['.gchoice_4_11_0', '.gchoice_4_11_1', '.gchoice_4_4_0', '.gchoice_4_4_1'];
    for ( var i = fields.length; i--; ) {
        $('#gravity_form_wrapper_ID').on('click', fields[i], function() {
            $('#WC_variation_drop_down_ID').val( $(this).children('input').val() ).trigger('change');
        });
    }
    

    Solution inspired by this post on setting WooCommerce Variation Fields.

    0 讨论(0)
  • 2020-12-02 11:43

    if anyone comes here like me to find the answer, I will provide a clarification in this.

    We have a problem implementing the change function because we need to know the price of variation selected but 'woocommerce_variation_select_change' we got the price from previous variation.

    So if you want to get the price of variation after change finish, you have to use 'woocommerce_variation_has_changed' jQuery function.

    Example:

    jQuery('#select_attribute_of_variation').on('woocommerce_variation_has_changed', function(){ // do your magic here... })

    0 讨论(0)
提交回复
热议问题