Skip to content
Advertisement

Add a Contact Form to “Out of Stock” product Variations in WooCommerce

I have successfully added a contact form to a product if it is Out of Stock using

add_action('woocommerce_single_product_summary', 'add_contact_form', 30,2);

function add_contact_form() {
    global $product;
        if(!$product->is_in_stock( )) {
           echo do_shortcode('[contact-form-7 id="6513" title="Out of Stock Form"]');
        }
    }

But I also want to add the same form if a products variation is Out of Stock too. Just unsure as to which hook I can use to tie it in to the Out of Stock message for that variation… I feel like it may be something to do with line 20 of woocommerce/single-product/add-to-cart/variation.php

<div class="woocommerce-variation-availability">{{{ data.variation.availability_html }}}</div>

But am getting a bit lost TBH.

I can change the text that is diaplyed for both simple products and those with variations by using

add_filter( 'woocommerce_get_availability', 'wcs_custom_get_availability', 1, 2);

function wcs_custom_get_availability( $availability, $_product ) {

    if ( ! $_product->is_in_stock() ) {
        $availability['availability'] = __('<h4 style="color:#F00;">Coming Soon</h4>', 'woocommerce');
    }

    return $availability;
    }

But if I try and add the Form Shortcode or other HTML, like an iFrame, it is stripped out and does not render.

Advertisement

Answer

The following code will add a contact form to a selected out of stock product variation:

add_filter( 'woocommerce_available_variation', 'form_to_out_of_stock_product_variations', 10, 3 );
function form_to_out_of_stock_product_variations( $data, $product, $variation ) {
    if( ! $data['is_in_stock'] )
        $data['availability_html'] .= do_shortcode('[contact-form-7 id="6513" title="Out of Stock Form"]');

    return $data;
}

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

enter image description here


So you will need to tweak your existing code as follow:

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="6513" title="Out of Stock Form"]');
}

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

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement