As Contact Form 7 allows hidden input field, you will set a hidden input field in your form for the product data (after the submit button) like:
<label> Your Name (required)
[text* your-name] </label>
<label> Your Email (required)
[email* your-email] </label>
<label> Your Message
[textarea* your-message] </label>
[submit "Send"]
[hidden your-product]
Then You will add it to the mail using for example:
Product Enquiry: [your-product]
Now jQuery will copy the product name (and the attribute Color value) to this hidden field. Replace your all existing related code with the following:
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"]'); // Here the contact form shortcode
if( $product->is_type('variable') ) {
echo '<div class="outofstock-form" style="display:none">' . $contact_form . '</div>';
} elseif( ! $product->is_in_stock() ) {
echo $contact_form;
?>
<script type="text/javascript">
jQuery(function($) {
var id = <?php echo $product->get_id(); ?>,
name = '<?php echo $product->get_name(); ?>';
$('input[name="your-product"]').val(name+' ('+id+')');
});
</script>
<?php
}
}
add_filter( 'woocommerce_available_variation', 'filter_available_variation_attributes', 10, 3 );
function filter_available_variation_attributes( $data, $product, $variation ){
if ( ! $data['is_in_stock'] ) {
$attribute = 'Color';
$term_name = $variation->get_attribute($attribute);
$data['name'] = $product->get_name();
$data['name'] .= $term_name ? ' - ' . $term_name : '';
}
return $data;
}
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'),
hiddenInputFieldObj = $('input[name="your-product"]');
$('form.variations_form').on('show_variation', function(event, data) { // On selected variation
if ( ! data.is_in_stock ) {
addToCartButtonObj.hide('fast');
contactFormObject.show('fast');
hiddenInputFieldObj.val(data.name+' ('+data.variation_id+')');
} else {
addToCartButtonObj.show('fast');
contactFormObject.hide('fast');
hiddenInputFieldObj.val('');
}
}).on('hide_variation', function() { // Not on selected variation
addToCartButtonObj.show('fast');
contactFormObject.hide('fast');
hiddenInputFieldObj.val('');
});
});
</script>
<?php
}
Code goes in functions.php file of the active child theme (or active theme). Tested and works.
Note: The code works for simple products and for variable products (product variations).
Related: