也许您可以使用一些jQuery和admin-ajax 做这个把戏。您还需要使用WooCommerce checkout field filters 要将“大学选择”字段添加到签出表单中。
如果您有冒险精神,可以添加一个自定义终点并使用WP REST API 而不是admin-ajax
.
我认为这样的做法应该奏效。此代码未经测试,请修改它以符合您的需要和设置。
Ajax PHP
function get_select_options() {
if ( empty( $_POST[\'type\'] ) || empty( $_POST[\'selected\'] ) ) {
wp_send_json_error();
}
if ( \'state\' === $_POST[\'type\'] ) {
$options_type = \'city\';
} else if ( \'city\' === $_POST[\'type\'] ) {
$options_type = \'university\';
} else {
$options_type = \'\';
}
if ( ! $options_type ) {
wp_send_json_error();
}
// Do your DB query to get options as an array with value => title pairs
$options = querySelectOptionsByType( $options_type );
if ( ! $options ) {
wp_send_json_error();
}
wp_send_json_success( array(
\'type\' => $options_type,
\'options\' => $options
) );
}
add_action( \'wp_ajax_get_select_options\', \'get_select_options\' );
add_action( \'wp_ajax_nopriv_get_select_options\', \'get_select_options\' );
如果WP数据库中有用于选择选项的自定义表,则应该能够
access them 具有
$wpdb 而且
jQuery,
jQuery(document).ready(function($) {
$(\'.conditional-select\').on(\'change\',function(event){
if ( \'state\' === this.name ) {
$(\'select[name="city"]\').empty().hide();
$(\'select[name="university"]\').empty().hide();
} else if ( \'city\' === this.name ) {
$(\'select[name="university"]\').empty().hide();
} else {
return;
}
getSelectOptions( this.name, this.value );
});
function getSelectOptions( currentSelect, selectedOption ) {
var data = {
\'action\': \'get_select_options\',
\'type\': currentSelect,
\'selected\': selectedOption
};
$.post( ajaxurl, data, function(response) {
if ( response.success ) {
var select = $(\'select[name="\' + response.data.type + \'"]\');
addOptionsToSelect( response.data.options, select );
$(select).show();
}
});
}
function addOptionsToSelect( options, select ) {
$(select).empty();
var optionsHtml = \'\';
$.each(options,function(i,option){
optionsHtml += getOptionString( option.value, option.title );
});
$(select).append(optionsHtml);
}
function getOptionString( value, title ) {
return \'<option value="\' + value + \'">\' + title + \'</option>\';
}
});