【发布时间】:2020-11-24 19:48:23
【问题描述】:
我有以下情况。我有 Contact Form 7 插件和几个具有不同服务的页面。每个页面都有一个联系表格,边栏中的选择下拉列表包含所有服务。 当您在特定服务中时,如何实现这一点,默认情况下会根据服务(可能通过 URL)自动选择下拉字段? 我没有找到这样的话题,我对这是如何发生的非常感兴趣。最好没有插件。在此先感谢:)
【问题讨论】:
我有以下情况。我有 Contact Form 7 插件和几个具有不同服务的页面。每个页面都有一个联系表格,边栏中的选择下拉列表包含所有服务。 当您在特定服务中时,如何实现这一点,默认情况下会根据服务(可能通过 URL)自动选择下拉字段? 我没有找到这样的话题,我对这是如何发生的非常感兴趣。最好没有插件。在此先感谢:)
【问题讨论】:
假设你有 3 个服务,服务 A,服务 B,服务 C,这样如果你在一个属于服务 B 的页面,URL 为domain.com/service-b/my-page,换句话说,该 URL 本身有足够的信息来确定此页面是服务 B 的一部分。有 2 种方法可以继续在您的下拉列表中实现自动选择,
1 在客户端,页面加载后使用 JavaScript,
使用以下脚本选择正确的选项,
(function($){
$(document).ready(function(){
//determine the current page,
let page = window.location.href, opt='';
//comment the following line for your site, this is only for this example test.
page = 'http://example.com/service-b/my-page';
switch(true){
case page.indexOf('service-b')>0:
opt='serviceb';
break;
case page.indexOf('service-c')>0:
opt='servicec';
break;
case page.indexOf('service-a')>0:
opt='servicea';
break;
}
$('select[name="select-services"]').find('option[value="'+opt+'"]').prop('selected', 'selected');
})
})(jQuery)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="select-services">
<option value="">select a service</option>
<option value="servicea">Service A</option>
<option value="serviceb">Service B</option>
<option value="servicec">Service C</option>
</select>
2 另一种方法是在页面加载之前使用 php 修改服务器端的选择选项,并挂钩过滤器“do_shortcode_tag”,一旦执行 cf7 表单简码,就会触发该过滤器。将以下代码放入您的主题functions.php 文件中,
add_filter('do_shortcode_tag','set_service',10,3);
function set_service($html, $attr, $tag){
//check this is a cf7 shortcode.
if('contact-form-7' !== $tag){
return $output;
}
//if you have several forms, you can also check this is the right form using $attr['id']
//determine which page you are on
global $wp;
$serv='';
switch(true){
case false !== strpos($wp->request, 'service-a' ):
$serv='servicea';
break;
case false !== strpos($wp->request, 'service-b' ):
$serv='serviceb';
break;
case false !== strpos($wp->request, 'service-c' ):
$serv='servicec';
break;
}
return str_replace('value="'.$serv.'"', 'value="'.$serv.'" selected="selected"', $html);
}
【讨论】:
你可以试试 wp filter hook:
add_filter( 'do_shortcode_tag','sercice_check',10,3);
function sercice_check($output, $tag, $attr){
// Checking your contact form id
// [contact-form-7 id="659" title="My Service"]
if( isset( $attr['id'] ) && $attr['id'] == 659 ){ //you can even check for specific attributes
global $wp;
$service='';
// Site url like : www.mysite.com/service/service-a/
switch(true){
case false !== strpos($wp->request, 'service-a' ):
$service='Service A';
break;
case false !== strpos($wp->request, 'service-a' ):
$service='Service B';
break;
}
return str_replace('value="'.$service.'"', 'value="'.$service.'" selected="selected"', $output);
}
return $output;
}
【讨论】: