Вы можете проверить эту мою статью, если вы хотите чего-то большего, чем просто скрыть / показать элементы: Вот как имитировать условные поля в CF7 с помощью jQuery .
Чтобы получить реальный образец того, что вы можете сделать, вы можете проверить этот сайт , выбрав вкладку "Richiedi quotazione". Сайт на итальянском, но легко даёт представление ...
Возвращаясь к моей статье, данный пример основан на предположении, что в реальных случаях вы можете иметь сложные условия (например, вы продаете продукты, которые могут быть стандартными, но также могут быть адаптированы).
- Стандартные продукты позволит пользователям выбирать код продукта, к которому
соответствуют заданной форме, ширине и высоте, а затем позволяют пользователю
введите только желаемую длину. Я также хочу, чтобы предварительный просмотр фигур отображался.
- Пользовательские продукты пользователи будут задавать форму, ширину, высоту и
длина.
Предпосылка заключается в том, что вы безопасно работаете над своей дочерней темой, поэтому, если вы все еще этого не делаете, сделайте это сейчас!
Код ссылается на ipotetical URL-адрес дочерней темы /wp-content/themes/myTheme-child
и его подкаталоги /catalogue
и /js
в домене my-domain.it
. Вам придется изменить эти значения в соответствии с вашей установкой WordPress.
ШАГ 1 : создайте свою контактную форму. Для данного примера я построил один: предполагается, что у вас есть файл myCatalogue.pdf
в подкаталоге /catalogue
вашей дочерней темы. Вот оно ...
<div class="myForm">
<fieldset name="customerInfo">
<ul class="selfClearCont">
<li><label for="your-name">Name (*):</label><br />
[text* your-name class:size-full default:user_first_name]</li>
<li><label for="your-email">E-mail (*):</label><br />
[email* your-email class:size-full default:user_email]</li>
<li><label for="your-tel">Telephone number:</label><br />
[text your-tel class:size-full]</li>
</ul>
</fieldset>
<p><strong>Subject: Quote request</strong></p>
<hr class="myHr selfClearCont"/>
<fieldset name="productType">
<p><label for="product-type">Product type (*):</label><br />
[select* productType include_blank "Standard" "Customized"]</p>
</fieldset>
<div id="standardProduct">
<fieldset name="productCode">
<ul class="selfClearCont">
<li class="floatLi"><label for="productCode">Product Code (*):</label><br />
[select* productCode include_blank "TEC01" "TEC02" "TEC03" "--"] <span class="SmallerText"><a href="http://www.my-domain.it/wp-content/themes/myTheme-child/catalogue/myCatalogue.pdf" title="Product catalogue with codes" target="_blank">Product catalogue</a></span></li>
<li id="productShape" class="floatLi lastFloatLi"></li>
</ul>
</fieldset>
</div>
<div id="customProduct">
<fieldset name="productShape">
<p><label for="productShape">Upload a shape image:</label><br />
[file productShape limit:1mb filetypes:bmp|cdr|dvg|dxf|gif|jpg|pdf|png|svg]<br />
<span class="SmallerText">(bmp, cdr, dvg, dxf, gif, jpg, pdf, png, svg)</span></p>
</fieldset>
</div>
<div id="productDimensions">
<fieldset name="productDimensions">
<ul class="selfClearCont">
<li class="floatLi"><label for="productWidth">Width (*):</label><span class="labelSusbt infoSubst">Width (*):</span><br />
[number* productWidth min:0 class:size-small]<span class="my-form-control size-small infoSubst lockedSubst widthSubst"></span><span class="SmallerText" style="margin-left:3px;">cm</span></li>
<li class="floatLi"><label for="productHeight">Height (*):</label><span class="labelSusbt infoSubst">Height (*):</span><br />
[number* productHeight min:0 class:size-small]<span class="my-form-control size-small infoSubst lockedSubst heightSubst"></span><span class="SmallerText" style="margin-left:3px;">cm</span></li>
<li class="floatLi lastFloatLi"><label for="productLenght">Lenght (*):</label><br />
[number* productLenght min:0 class:size-small]<span class="SmallerText" style="margin-left:3px;">cm</span></li>
</ul>
</fieldset>
</div>
<hr class="myHr selfClearCont"/>
<fieldset name="otherInfo">
<p><label for="your-message">Notes e messages:</label><br />
[textarea your-message class:size-full]</p>
<p><strong>By selecting this checbox</strong> [acceptance Privacy default:off] (*) I accept your privacy policy.</p>
<p><label for="MyCaptchac">Captcha (*):</label><br />
<span class="MyCaptchac">[captchac captcha size:m]</span> <span class="MyCaptchar">[captchar captcha class:size-small]</span></p>
</fieldset>
<p>[submit "Send"]</p>
</div>
ШАГ 2 : стилизовать вашу контактную форму с соответствующим набором директив CSS. Мой содержит некоторые директивы для управления классами, которые я также добавляю через jQuery. Вот оно ...
/* Contact Form 7 */
.myForm {width: 300px;}
.wpcf7-select.wpcf7-form-control,
.wpcf7-select.my-form-control {
-moz-box-shadow: rgba(0,0,0,.2) 0 1px 4px inset;
-webkit-box-shadow: rgba(0,0,0,.2) 0 1px 4px inset;
box-shadow: rgba(0,0,0,.2) 0 1px 4px inset;
}
.wpcf7-text.wpcf7-form-control,
.wpcf7-email.wpcf7-form-control,
.wpcf7-number.wpcf7-form-control,
.wpcf7-textarea.wpcf7-form-control,
.my-form-control {
border: 1px solid #aaa;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
-moz-box-shadow: rgba(0,0,0,.2) 0 1px 4px inset;
-webkit-box-shadow: rgba(0,0,0,.2) 0 1px 4px inset;
box-shadow: rgba(0,0,0,.2) 0 1px 4px inset;
height:1.4em;
line-height: 1.20em;
}
textarea.wpcf7-textarea.wpcf7-form-control,
textarea.my-form-control {height: auto; min-height: 100px; resize: vertical; }
.wpcf7-form-control:focus {
border: 1px solid #0000cc !important;
outline: none;
box-shadow: none;
-moz-box-shadow: none;
-webkit-box-shadow: none;
}
.wpcf7-form-control.floatCtrl,
.my-form-control.floatCtrl {float:left;}
.wpcf7-form-control.size-small,
.my-form-control.size-small {width:44px;}
.wpcf7-form-control.size-full,
.my-form-control.size-full {width:100%;}
img.productShape {width: 150px;}
.lockedField,
.infoSubst {display:none;}
.infoSubst.lockedSubst {
float: left;
background-color:rgba(0,0,0,.2);
font-family: Arial;
font-size: 12.6666669845581px;
padding-top: 1px;
border: 1px solid #aaa;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
-moz-box-shadow: rgba(0,0,0,.2) 0 1px 4px inset;
-webkit-box-shadow: rgba(0,0,0,.2) 0 1px 4px inset;
box-shadow: rgba(0,0,0,.2) 0 1px 4px inset;
height:1.4em;
line-height: 1.20em;
}
/* CF7 Submit button */
.wpcf7-submit.wpcf7-form-control {
float: right;
padding: .5em 2em;
border: 1px solid #666;
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 10px;
-moz-box-shadow: 0 0 .5em rgba(0, 0, 0, .8);
-webkit-box-shadow: 0 0 .5em rgba(0, 0, 0, .8);
box-shadow: 0 0 .5em rgba(0, 0, 0, .8);
color: #fff;
background: #0a0;
font-size: 1em;
line-height: 1em;
font-weight: bold;
opacity: .7;
-webkit-appearance: none;
-moz-transition: opacity .5s;
-webkit-transition: opacity .5s;
-o-transition: opacity .5s;
transition: opacity .5s;
}
.wpcf7-submit.wpcf7-form-control:hover,
.wpcf7-submit.wpcf7-form-control:active {
cursor: pointer;
opacity: 1;
}
.wpcf7-submit.wpcf7-form-control:active {
color: #333;
background: #eee;
-moz-box-shadow: 0 0 .5em rgba(0, 0, 0, .8) inset;
-webkit-box-shadow: 0 0 .5em rgba(0, 0, 0, .8) inset;
box-shadow: 0 0 .5em rgba(0, 0, 0, .8) inset;
}
.wpcf7-submit.wpcf7-form-control:disabled {
-moz-box-shadow: 0 0 .5em rgba(0, 0, 0, .8);
-webkit-box-shadow: 0 0 .5em rgba(0, 0, 0, .8);
box-shadow: 0 0 .5em rgba(0, 0, 0, .8);
color: #fff;
background: #0a0;
opacity: .7;
cursor: not-allowed;
}
/* END of CF7 Submit button */
/* END of Contact Form 7 */
/* Clearing Classes */
ul.selfClearCont {
display: block;
clear: both;
padding: 0 !important;
margin: 0 !important;
}
ul.selfClearCont li {
list-style-type: none;
padding: 0 0 10px 0 !important;
}
li.floatLi {
list-style-type: none;
display: inline-block;
float: left;
margin: 0 30px 0 0 !important;
}
li.floatLi.lastFloatLi {
margin-right: 0px !important;
}
.selfClearCont:before,
.selfClearCont:after {
content:"";
display:table;
}
.selfClearCont:after {
clear:both;
}
.selfClearCont {
zoom:1; /* For IE 6/7 (trigger hasLayout) */
}
/* END of Clearing Classes */
ШАГ 3 : запишите некоторые функции для управления грязной работой. Моя задача позаботиться о проверке условий, показать / скрыть соответствующие поля, предварительно установленные значения, заменить предварительно установленные поля серыми информационными полями, показать предварительный просмотр формы продукта. Вам нужно сохранить его как Cond1.js
в подкаталоге /js
нашей дочерней темы, чтобы он работал с данным примером. Вам также необходимо сохранить некоторые .jpg
в подкаталоге /catalogue
вашей дочерней темы, чтобы предварительный просмотр формы продукта работал правильно. А вот и код ...
jQuery.noConflict();
jQuery(document).ready(function($) {
/* auto-classes for form fields based on their name */
$(".wpcf7-form-control[name]").each(function() {
var MyClass = $(this).attr("name");
$(this).addClass (MyClass);
});
/* auto-classes for form labels based on their for */
$("label[for]").each(function() {
var MyClass = $(this).attr("for");
$(this).addClass (MyClass);
});
/* title for disabled submit button */
$("input.wpcf7-submit").attr( "title", "Please accept our privacy policy to continue" );
$("input.Privacy").change(function() {
if ($(this).prop('checked') == true) {
$("input.wpcf7-submit").attr( "title", "Send your request" );
}
else {
$("input.wpcf7-submit").attr( "title", "Please accept our privacy policy to continue" );
}
});
function myCFReset() {
$("#standardProduct, #customProduct, #productDimensions, .infoSubst").hide();
$(".widthSubst, .heightSubst, #productShape").html("");
$("input.productWidth, input.productHeight").val("").removeClass("lockedField");
$("label.productWidth, label.productHeight").removeClass("lockedField");
$("select.productCode, input.productLenght").val("").removeClass("floatCtrl");
}
myCFReset();
$("select.productType").change(function() {
if ($(this).val() == "Standard") {
myCFReset();
$("#standardProduct").show();
$("input.productWidth, input.productHeight, label.productWidth, label.productHeight").addClass("lockedField");
$("input.productLenght").addClass("floatCtrl");
}
else if ($(this).val() == "Customized") {
myCFReset();
$("select.productCode").val("--");
$("#customProduct, #productDimensions").show();
}
else {
myCFReset();
}
});
$("select.productCode").change(function() {
if ($(this).val() == "" || $(this).val() == "--") {
$("#productShape, .widthSubst, .heightSubst").html("");
$("input.productWidth, input.productHeight, input.productLenght").val("");
$("#productDimensions").hide();
}
else {
var targetCode = $("select.productCode").val();
var activeCodes = [
"TEC01", 12, 5, "TEC02", 15, 4, "TEC03", 12, 3
];
var ImgBaseURL = "http://www.my-domain.it/wp-content/themes/myTheme-child/catalogue/";
var imageExt = ".jpg";
var ImgURL = ImgBaseURL + targetCode + imageExt;
var MyTitle = '<img class="productShape" title="Our product code '+ targetCode + '" ';
var MyAlt = 'alt="Our product code '+ targetCode + '" ';
var MySrc = 'src="'+ ImgURL + '" />';
$("#productShape").html(MyTitle + MyAlt + MySrc);
var id = $.inArray(targetCode, activeCodes);
$("input.productWidth").val(activeCodes[id+1]);
$("input.productHeight").val(activeCodes[id+2]);
$(".widthSubst").html(activeCodes[id+1].toString());
$(".heightSubst").html(activeCodes[id+2].toString());
$(".infoSubst, #productDimensions").show();
}
});
});
ШАГ 4 : поставьте в очередь файл jQuery Cond1.js
на нужной странице / записи или страницах / публикациях. Я подготовил следующий код для добавления в functions.php
вашей дочерней темы: он предполагает, что вы поместили форму в идентификатор страницы 1; измените это в соответствии с вашими потребностями. Вот код ...
function loadMyScripts() {
/* Common scripts */
// insert here the scripts you want for every page
/* END of common scripts */
/* Page-based scripts */
$pageId = get_the_ID();
$pageType = get_post_type();
/* you can enqueue scripts based on post-type (e.g. for all product post-type)
if($pageType == "product") {
wp_enqueue_script('CondAll', get_stylesheet_directory_uri() . '/js/CondAll.js', array('jquery'));
}
or you can do it based on a particular post/page id
if($pageId == "294") {
wp_enqueue_script('Cond294', get_stylesheet_directory_uri() . '/js/Cond294.js', array('jquery'));
}
*/
/* for the example, we imagine to load a script called Cond1 for post id=1 */
if($pageId == "1") {
wp_enqueue_script('Cond1', get_stylesheet_directory_uri() . '/js/Cond1.js', array('jquery'));
}
/* END of page-based scripts */
}
add_action( 'wp_enqueue_scripts', 'loadMyScripts' );
Вот и все.