你的 JS 代码中有额外的括号,但除此之外它是有效的。您确定第三个服务的页面引用包含正确的 slugservice-c
?
选项A:
这是一个演示:https://jsfiddle.net/9z5m4syd/2/ https://jsfiddle.net/9z5m4syd/2/
更新后的JS代码:
$(document).ready(function() {
// determine the previous page
// eg. page referrer
let page = 'http://website.domain/service-c', opt='';
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;
}
// Run this after 1.5 seconds
setTimeout(function() {
$('select[name="select-services"]').find('option[value="'+opt+'"]').prop('selected', 'selected');
}, 1500);
})(jQuery);
选项B:
创建自定义表单标签并选择课程服务器端。
新的表单标签:[courses your-field-name]
添加到functions.php:
/**
* Register a new CF7 form tag.
*
* Use this tag in your form [courses your-field-name]
*/
add_action( 'wpcf7_init', 'custom_add_form_tag_courses' );
function custom_add_form_tag_courses() {
wpcf7_add_form_tag( array( 'courses', 'courses*' ), 'custom_courses_form_tag_handler', true );
}
/**
* CF7 callback function that parses the form tag.
*/
function custom_courses_form_tag_handler( $tag ) {
$tag = new WPCF7_FormTag( $tag );
if ( empty( $tag->name ) ) {
return '';
}
$custom_select = '';
$option = '';
// Retrieve referer from ‘_wp_http_referer’ or HTTP referer.
$page_referrer = wp_get_referer();
// List of courses.
$courses = array(
"Alege cursul",
"CURS MAKEUP",
"CURS EXTENSII GENE",
"CURS STILIST PROTEZIST UNGHII",
"CURS COSMETICA",
"CURS MASAJ",
"CURS DESIGN INTERIOR",
"CURS FRIZERIE/BARBERING",
"CURS MANICHIURIST PEDICHIURIST",
"CURS DECORATOR FLORAL",
"CURS EPILARE",
"CURS FOTOGRAFIE",
"CURS VIDEO",
"CURS MICRONEEDLING",
"CURS COAFOR",
"CURS DE EXTENSII PAR",
"CURS COLORIMETRIE",
"CURS CROITORIE",
"CURS STILISM VESTIMENTAR",
"CURS CONSTRUCTIE TIPARE",
"WORKSHOP STILIZARE SPRANCENE",
"WORKSHOP COMBI DRY MANICURE",
"WORKSHOP AUTO COAFAT",
"WORKSHOP IMPLETITURI"
);
// Loop through all the courses and create option values.
foreach( $courses as $course ) {
// Generate course slug.
$slug = sanitize_title( $course );
// Search for course in page referrer.
$match = stripos( $page_referrer, $slug );
// Check if referrer exists and compare it to the course list.
if ( ! empty( $page_referrer ) && $match !== false ) {
$option .= sprintf( '<option value="%1$s" selected="selected">%2$s</option>', esc_html( $slug ), esc_html( $course ) );
} else {
$option .= sprintf( '<option value="%1$s">%2$s</option>', esc_html( $slug ), esc_html( $course ) );
}
}
// Add previously generated list of options to the select tag.
$custom_select = sprintf( '<select name="%1$s" id="%2$s">%3$s</select>', $tag->name, esc_attr( $tag->name . '-options' ), $option );
return $custom_select;
}