Home » Wordpress » Woocommerce: custom image for product variations

Woocommerce: custom image for product variations

Posted by: admin February 26, 2018 Leave a comment

Questions:

I’m working on writing a plugin that will filter on “woocommerce_single_product_image_html” to display a custom image for the product.

I’m having trouble grabbing the values of the dropdown boxes via jquery. So far i’ve tried:

jQuery(document).ready(function($) {
    // Code here will be executed on document ready. Use $ as normal.

    $('#color').change(function() {
            var selected = $(this).children("option").filter(":selected").text();
            alert(selected);
    });
});

I have been able to verify that the above code works by appending “.change()” to trigger the change event on load, but its not triggered when changing selections in the dropdown box. My guess is that this is conflicting with the core change event from woocommerece. Any suggestions on how I can accomplish this via a plugin?

Answers:

So, I finally tracked this down. One of the woocommerce javascript files (assets/js/frontend/add-to-cart-variation.js) was issuing the following command to unbind all change events, which explains why mine wasn’t firing.

this.find( '.variations select' ).unbind( 'change focusin' );

My solution was to write a basic plugin to add in my functionality. Luckily, the woocommerce_variable_add_to_cart function is pluggable, so I was able to make a copy of it and tweak it to load my own version of the add-to-cart-variation.js file without the above unbind line. This way the core plugin code remains unmodified.

function woocommerce_variable_add_to_cart() {
    global $product;

    // Enqueue variation scripts
    wp_deregister_script( 'wc-add-to-cart-variation' );
    wp_register_script( 'wc-add-to-cart-variation', plugins_url( '/js/add-to-cart-variation.js', __FILE__ ), array( 'jquery' ), WC_VERSION, true );
    wp_enqueue_script( 'wc-add-to-cart-variation' );

    // Load the template
    wc_get_template( 'single-product/add-to-cart/variable.php', array(
        'available_variations'  => $product->get_available_variations(),
        'attributes'            => $product->get_variation_attributes(),
        'selected_attributes'   => $product->get_variation_default_attributes()
    ) );
}

Hopefully someone else also finds this info helpful!