Search code examples
phpjquerywoocommercecontact-form-7product-variations

Display a form when the selected variation is out of stock in WooCommerce


In WooCommerce with Contact Form 7 plugin, I have added a form to my out of stock simple products, on single product pages, using the following code:

add_action( 'woocommerce_single_product_summary', 'add_contact_form', 30, 2 );
function add_contact_form() {
    global $product;

    if( ! $product->is_in_stock( ) && ! $product->is_type('variable') ) {
       echo do_shortcode('[contact-form-7 id="14880" title="Fiyat Sorunuz"]');
    }
}

This "out of stock" form works just well for simple products:

out of stock form works


But doesn't work on "out of stock" product variations for variable products:

only out of stock. How can I add a variant form?

How can I display this form for selected product variation that are out of stock?

Any help is appreciated.


Solution

  • This requires a little change in your code and some jQuery code to show/hide the contact form (and the add to cart button) on variable products, depending on the selected product variation stock status.

    The replacement code for simple and variable products:

    add_action( 'woocommerce_single_product_summary', 'add_product_outofstock_contact_form', 30, 2 );
    function add_product_outofstock_contact_form() {
        global $product;
    
        $contact_form = do_shortcode('[contact-form-7 id="14880" title="Fiyat Sorunuz"]');
    
        if( $product->is_type('variable') ) {
            echo '<div class="outofstock-form" style="display:none">' . $contact_form . '</div>';
        } elseif( ! $product->is_in_stock() ) {
            echo $contact_form;
        }
    }
    
    add_action('woocommerce_after_variations_form', 'outofstock_product_variation_js');
    function outofstock_product_variation_js() {
        ?>
        <script type="text/javascript">
        jQuery(function($) {
            var contactFormObject  = $('.outofstock-form'),
                addToCartButtonObj = $('.woocommerce-variation-add-to-cart');
    
            $('form.variations_form').on('show_variation', function(event, data) { // No selected variation
                if ( ! data.is_in_stock  ) {
                    addToCartButtonObj.hide('fast');
                    contactFormObject.show('fast');
                } else {
                    addToCartButtonObj.show('fast');
                    contactFormObject.hide('fast');
                }
            }).on('hide_variation', function() { // Not on selected variation
                addToCartButtonObj.show('fast');
                contactFormObject.hide('fast');
            });
        });
        </script>
        <?php
    }
    

    Code goes in functions.php file of the active child theme (or active theme). Tested and works.

    Related: Pass the chosen product variations data into Contact Form 7 enquiry form