Pass the chosen product variations data into Contact Form 7 enquiry form
UPDATED: Added WC 3+ compatibility
I have tested it and it will not send any data related to chosen variations, because it is just outputting the selected contact form below add-to-cart button (in single products pages). Additionally this plugin hasn't been updated since more than 2 years, so it's some kind of outdated.
THE GOOD NEW: A WORKING SOLUTION
I have found this related answer: Product Name WooCommerce in Contact Form 7
It explains how to set a contact form 7 shortcode in a product tab and displaying the chosen product title in the email.
So from this answer I have transposed the code, to use it just as the plugin was doing (just below the add to cart button).
Here in this example/answer I have set in my variable product 2 attributes for the product variations: Color
and Size
.
This are my settings Contact form 7
for the form that I will use in my code:
<label> Your Name (required)
[text* your-name] </label>
<label> Your Email (required)
[email* your-email] </label>
<label> Subject (required)
[text* your-subject class:product_name] </label>
<label> Your Message
[textarea your-message] </label>
[submit "Send"]
[text your-product class:product_details]
Here I have add this text field [text your-product class:product_details]
. so you will need to add also in your "mail" settings tab [your-product]
tag inside the "message body", to get that in your email:
From: [your-name] <[your-email]>
Subject: [your-subject]
Product: [your-product]
Message Body:
[your-message]
--------------
This e-mail was sent from a contact form 7
The PHP code custom funtion hooked in woocommerce_after_add_to_cart_form
action hook:
add_action( 'woocommerce_after_add_to_cart_form', 'product_enquiry_custom_form' );
function product_enquiry_custom_form() {
global $product, $post;
// Set HERE your Contact Form 7 shortcode:
$contact_form_shortcode = '[contact-form-7 id="382" title="form"]';
// compatibility with WC +3
$product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;
$product_title = $post->post_title;
// The email subject for the "Subject Field"
$email_subject = __( 'Enquire about', 'woocommerce' ) . ' ' . $product_title;
foreach($product->get_available_variations() as $variation){
$variation_id = $variation['variation_id'];
foreach($variation['attributes'] as $key => $value){
$key = ucfirst( str_replace( 'attribute_pa_', '', $key ) );
$variations_attributes[$variation_id][$key] = $value;
}
}
// Just for testing the output of $variations_attributes
// echo '<pre>'; print_r( $variations_attributes ); echo '</pre>';
## CSS INJECTED RULES ## (You can also remve this and add the CSS to the style.css file of your theme
?>
<style>
.wpcf7-form-control-wrap.your-product{ opacity:0;width:0px;height:0px;overflow: hidden;display:block;margin:0;padding:0;}
</style>
<?php
// Displaying the title for the form (optional)
echo '<h3>'.$email_subject.'</h3><br>
<div class="enquiry-form">' . do_shortcode( $contact_form_shortcode ) . '</div>';
## THE JQUERY SCRIPT ##
?>
<script>
(function($){
<?php
// Passing the product variations attributes array to javascript
$js_array = json_encode($variations_attributes);
echo 'var $variationsAttributes = '. $js_array ;
?>
// Displaying the subject in the subject field
$('.product_name').val('<?php echo $email_subject; ?>');
////////// ATTRIBUTES VARIATIONS SECTION ///////////
var $attributes;
$('td.value select').blur(function() {
var $variationId = $('input[name="variation_id"]').val();
// console.log('variationId: '+$variationId);
if (typeof $variationId !== 'undefined' ){
for(key in $variationsAttributes){
if( key == $variationId ){
$attributes = $variationsAttributes[key];
break;
}
}
}
if ( typeof $attributes !== 'undefined' ){
// console.log('Attributes: '+JSON.stringify($attributes));
var $attributesString = '';
for(var attrKey in $attributes){
$attributesString += ' ' + attrKey + ': ' + $attributes[attrKey] + ' — ';
}
$('.product_details').val( 'Product <?php echo $product_title; ?> (ID <?php echo $product_id; ?>): ' + $attributesString );
}
});
})(jQuery);
</script>
<?php
}
Code goes in function.php file of your active child theme (or theme) or also in any plugin file.
You will get exactly what the plugin was doing with that additionals features:
- A custom product title, as subject of the mail.
- The selected variation attributes Name label + values in the additional fiels (that will be hidden).
Here are the screen shoots from my test server:
The product with the selected attributes:
What I get on the form (I dont hide the special text field to show you the pulled data by jQuery):
As you see, you get the data you need to send in your email…
Once I have selected the attributes of the product and filled the other fields of the form, when I submit this form I get, this email message:
From: John Smith <j.smith@themain.com>
Subject: Enquire about Ship Your Idea
Product: Product Ship Your Idea (ID 40): Color: black — Size: 12 —
Message Body:
I send this request about this very nice product … I send this request about this very nice product …
--
This e-mail was sent from a contact form 7
So everithing is working just as you expected and this is a working tested example answer.
Pass some WooCommerce product data to Contact Form 7 enquiry form
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:
- Pass the chosen product variations data into Contact Form 7 enquiry form
- Display a form when the selected variation is out of stock in WooCommerce
Display a form when the selected variation is out of stock in WooCommerce
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
Product Name WooCommerce in Contact Form 7
I don't know how did you add tab as you have not mentioned anything ..
But you can achieve by adding following code in to your theme's functions.php
:
add_filter( 'woocommerce_product_tabs', 'product_enquiry_tab' );
function product_enquiry_tab( $tabs ) {
$tabs['test_tab'] = array(
'title' => __( 'Enquire about Product', 'woocommerce' ),
'priority' => 50,
'callback' => 'product_enquiry_tab_form'
);
return $tabs;
}
function product_enquiry_tab_form() {
global $product;
//If you want to have product ID also
//$product_id = $product->id;
$subject = "Enquire about ".$product->post->post_title;
echo "<h3>".$subject."</h3>";
echo do_shortcode('[contact-form-7 id="19" title="Contact form 1_copy"]'); //add your contact form shortcode here ..
?>
<script>
(function($){
$(".product_name").val("<?php echo $subject; ?>");
})(jQuery);
</script>
<?php
}
?>
Also add class to your contact form :
<p>Your Name (required)<br />
[text* your-name] </p>
<p>Your Email (required)<br />
[email* your-email] </p>
<p class="product_subject">Subject<br />
[text your-subject class:product_name] </p>
<p>Your Message<br />
[textarea your-message] </p>
<p>[submit "Send"]</p>
Bingo ! You have just achieved what you wanted.
Screen shot
Comment if you have any doubt.
Contact Form 7 Dropdown Force Required?
It looks like the form is being sent, because the select fields are indeed always filled out. You forgot the "include_blank" attribute:
[select* menu-834 include_blank "product 1" "product 2" "product 3"]
It inserts a blank item into the top of options of the drop-down menu which evaluates as not-filled-out.
See docs for include_blank
option in drop-down menus:
https://contactform7.com/checkboxes-radio-buttons-and-menus/#select
How to add Phone no field in enquiry form of woocommerce product page
NOTE : Take back up before implementing this.
Go to wp-content > plugins > product-enquiry-for-woocommerce > data >contact.php
And replace content of contact.php
with following code :
<?php
/* SimpleModal Contact Form
* http://simplemodal.com/
* http://code.google.com/p/simplemodal/
*
* Copyright (c) 2012 Eric Martin - http://ericmmartin.com
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/mit-license.php
*
* Revision: $Id: contact-dist.php 269 2011-12-17 23:24:14Z emartin24 $
*
*/
//date_default_timezone_set('America/Los_Angeles');
global $to;
if(isset($_POST['wdm_form_dataset']))
{
$form_data = $_POST['wdm_form_dataset'];
}
if(isset($_POST['wdm_admin_email']))
{
$to_adm = $_POST['wdm_admin_email'];
}
if(isset($_POST['wdm_site_name']))
{
$site_name = $_POST['wdm_site_name'];
}
// User settings
if (!empty($form_data['user_email']))
$to = $form_data['user_email'];
else if(isset($to_adm))
$to = $to_adm;
if (!empty($form_data['default_sub']))
$subject = $form_data['default_sub'];
else if(isset($site_name))
$subject = "Enquiry for a product from ".$site_name;
//Include extra form fields and/or submitter data?
//false = do not include
$extra = array(
"form_subject" => true,
"your_number" =>true,
"form_cc" => (isset($form_data['enable_send_mail_copy']) ? true : false),
"ip" => false,
"user_agent" => false
);
// Process
$action = isset($_POST["action"]) ? $_POST["action"] : "";
if (empty($action)) {
// Send back the contact form HTML
$output = "<div style='display:none'>
<div class='contact-top'></div>
<div class='contact-content'>
<h1 class='contact-title'>Product Enquiry:</h1>
<div class='contact-loading' style='display:none'></div>
<div class='contact-message' style='display:none'></div>
<form action='#' style='display:none'>
<input type='text' id='wdm_product_name' class='contact-input' name='wdm_product_name' value='' readonly=true />
<label for='contact-name'>*Name:</label>
<input type='text' id='contact-name' class='contact-input' name='name' tabindex='1001' />
<label for='contact-email'>*Email:</label>
<input type='text' id='contact-email' class='contact-input' name='email' tabindex='1002' />";
if ($extra["form_subject"] && $extra["your_number"]) {
$output .= "
<label for='contact-subject'>Subject:</label>
<input type='text' id='contact-subject' class='contact-input' name='subject' value='' tabindex='1003' />";
$output .= "
<label for='contact-phone'>Phone Number:</label>
<input type='text' id='contact-phone' class='contact-input' name='phone' value='' tabindex='1007' />";
}
$output .= "<input type='hidden' id='wdm_product_url' class='contact-input' name='wdm_product_url' value='' />";
$output .= "<input type='hidden' id='wdm_form_mail_to' class='contact-input' name='wdm_form_mail_to' value='' />";
$output .= "<input type='hidden' id='wdm_form_def_sub' class='contact-input' name='wdm_form_def_sub' value='' />";
$output .= "<input type='hidden' id='wdm_website_name' class='contact-input' name='wdm_website_name' value='' />";
$output .= "
<label for='contact-message'>*Enquiry:</label>
<textarea id='contact-message' class='contact-input' name='message' cols='40' rows='4' tabindex='1004'></textarea>
<br/>";
if ($extra["form_cc"]) {
$output .= "
<label> </label>
<input type='checkbox' id='contact-cc' name='cc' value='1' tabindex='1005' /> <span class='contact-cc'>Send me a copy</span>
<br/>";
}
$output .= "
<label> </label>
<button type='submit' class='contact-send contact-button' tabindex='1006'>Send</button>
<button type='submit' class='contact-cancel contact-button simplemodal-close' tabindex='1007'>Cancel</button>
<br/>
<input type='hidden' name='token' value='" . smcf_token($to) . "'/>
</form>
</div>
<div class='contact-bottom'><a href='http://wisdmlabs.com' target='_blank'>Powered by WisdmLabs</a></div>
</div>";
echo $output;
$to = base64_encode($to);
$subject = base64_encode($subject);
$site_name = base64_encode($site_name);
echo '<script type="text/javascript">
jQuery(document).ready(
function()
{
jQuery("#wdm_form_mail_to").val("'.$to.'");
jQuery("#wdm_form_def_sub").val("'.$subject.'");
jQuery("#wdm_website_name").val("'.$site_name.'");
}
);
</script>';
}
else if ($action == "wdm_send") {
// Send the email
//echo "<pre>";print_r($_REQUEST);echo "</pre>";exit;
$name = isset($_POST["name"]) ? $_POST["name"] : "";
$email = isset($_POST["email"]) ? $_POST["email"] : "";
$urphone = isset($_POST["phone"]) ? $_POST["phone"] : "";
$subject = isset($_POST["wdm_form_def_sub"]) ? $_POST["wdm_form_def_sub"] : "";
$subject = base64_decode($subject);
$subject = !empty($_POST["subject"]) ? $_POST["subject"] : $subject;
$product_url = isset($_POST["wdm_product_url"]) ? $_POST["wdm_product_url"] : "";
$product_name = isset($_POST["wdm_product_name"]) ? $_POST["wdm_product_name"] : "";
$message = isset($_POST["message"]) ? $_POST["message"] : "";
$cc = isset($_POST["cc"]) ? $_POST["cc"] : "";
$token = isset($_POST["token"]) ? $_POST["token"] : "";
$to = isset($_POST["wdm_form_mail_to"]) ? $_POST["wdm_form_mail_to"] : "";
$to = base64_decode($to);
//echo $to;exit;
$site_name = isset($_POST["wdm_website_name"]) ? $_POST["wdm_website_name"] : "";
$site_name = base64_decode($site_name);
// make sure the token matches
if ($token === smcf_token($to)) {
smcf_send($name, $email, $subject, $urphone, $product_url, $product_name, $site_name, $message, $cc);
echo "Your enquiry sent successfully. We will get back to you soon.";
}
else {
echo "Unfortunately, your enquiry could not be verified.";
}
}
function smcf_token($s) {
return md5("smcf-" . $s . date("WY"));
}
// Validate and send email
function smcf_send($name, $email, $subject, $urphone, $product_url, $product_name, $site_name, $message, $cc) {
global $to, $extra;
// Filter and validate fields
$name = smcf_filter($name);
$subject = smcf_filter($subject);
$email = smcf_filter($email);
if (!smcf_validate_email($email)) {
$subject .= " - invalid email";
$message .= "\n\nBad email: $email";
$email = $to;
$cc = 0; // do not CC "sender"
}
// Add additional info to the message
if ($extra["ip"]) {
$message .= "\n\nIP: " . $_SERVER["REMOTE_ADDR"];
}
if ($extra["user_agent"]) {
$message .= "\n\nUSER AGENT: " . $_SERVER["HTTP_USER_AGENT"];
}
// Set and wordwrap message body
$body = "Product Enquiry from <strong>". $site_name . "</strong> <br /><br />";
$body .= "<strong>Product Name:</strong> '". $product_name ."'<br /><br />";
$body .= "<strong>Product URL:</strong> ". $product_url ."<br /><br />";
$body .= "<strong>Customer Name:</strong> ". $name ."<br /><br />";
$body .= "<strong>Customer Email:</strong> ". $email ."<br /><br />";
$body .= "<strong>Customer Phone Number:</strong> ". $urphone ."<br /><br />";
$body .= "<strong>Message:</strong> <br />". $message;
$body = wordwrap($body, 100);
// Build header
$headers = "From: $email\n";
$headers .= "Reply-To: $email \n";
if ($cc == 1) {
$headers .= "Cc: $email\n";
}
// $headers .= "X-Mailer: PHP/SimpleModalContactForm";
// UTF-8
if (function_exists('mb_encode_mimeheader')) {
$subject = mb_encode_mimeheader($subject, "UTF-8", "B", "\n");
}
else {
// you need to enable mb_encode_mimeheader or risk
// getting emails that are not UTF-8 encoded
}
$headers .= "MIME-Version: 1.0\n";
$headers .= "Content-type: text/html; charset=utf-8\n";
$headers .= "Content-Transfer-Encoding: quoted-printable\n";
//echo "to ".$to."<br>";
//echo "subject ".$subject."<br>";
//echo "body ".$body."<br>";
//echo "headers ".$headers."<br>";exit;
wp_mail($to, $subject, $body, $headers) or die("Unfortunately, a server issue prevented delivery of your message.");
//wp_mail($to, $subject, $body, $headers) or
// die("Unfortunately, a server issue prevented delivery of your message.");
}
// Remove any un-safe values to prevent email injection
function smcf_filter($value) {
$pattern = array("/\n/","/\r/","/content-type:/i","/to:/i", "/from:/i", "/cc:/i");
$value = preg_replace($pattern, "", $value);
return $value;
}
// Validate email address format in case client-side validation "fails"
function smcf_validate_email($email) {
$at = strrpos($email, "@");
// Make sure the at (@) sybmol exists and
// it is not the first or last character
if ($at && ($at < 1 || ($at + 1) == strlen($email)))
return false;
// Make sure there aren't multiple periods together
if (preg_match("/(\.{2,})/", $email))
return false;
// Break up the local and domain portions
$local = substr($email, 0, $at);
$domain = substr($email, $at + 1);
// Check lengths
$locLen = strlen($local);
$domLen = strlen($domain);
if ($locLen < 1 || $locLen > 64 || $domLen < 4 || $domLen > 255)
return false;
// Make sure local and domain don't start with or end with a period
if (preg_match("/(^\.|\.$)/", $local) || preg_match("/(^\.|\.$)/", $domain))
return false;
// Check for quoted-string addresses
// Since almost anything is allowed in a quoted-string address,
// we're just going to let them go through
if (!preg_match('/^"(.+)"$/', $local)) {
// It's a dot-string address...check for valid characters
if (!preg_match('/^[-a-zA-Z0-9!#$%*\/?|^{}`~&\'+=_\.]*$/', $local))
return false;
}
// Make sure domain contains only valid characters and at least one period
if (!preg_match("/^[-a-zA-Z0-9\.]*$/", $domain) || !strpos($domain, "."))
return false;
return true;
}
//exit;
?>
Reminder: Plugin providing that feature in PRO
version.So please use that.I am posting it just for temporary usage and I have not seen its License of usage.
Please let me know either its working or not because its UNTESTED.
Related Topics
PHP Session Variables Not Preserved with Ajax
PHP - Syntax Error, Unexpected T_Constant_Encapsed_String
What Does PHP Do with Deprecated Functions
Laravel Form Methods VS Traditional Coding
Adding Additional Persist Calls to Preupdate Call in Symfony 2.1
Codeigniter "Flashdata" Doesn't Work
Easiest Way to Grab Filesize of Remote File in PHP
Installing Mcrypt on Osx 10.8.2 - PHP 5.3.15 with Homebrew
How to Convert a Huge Integer to Hex in PHP
Do I Need to Escape My Variables If I Use MySQLi Prepared Statements
How to Convert an Iso8601 Date to Another Format in PHP
Php: Remote Function Call and Returning the Result
How to Check Whether Suhosin Is Installed
PHP Xml Inserting Element After (Or Before) Another Element
Can't Connect to Postgresql with PHP Pg_Connect()
If I Use Captcha Will I Be Able to Stop the Spam Completely in My Blog