我有一个动态相关的选择下拉列表系统,可以从数据库中选择车辆的制造商和型号,效果很好,但是我想将其转换为使用并从wordpress中选择父类别和子类别,而不是使用sql dump中的信息。我有帖子元make
,而帖子元model
和model
元是make
元的子类别。我只是想知道如何编写函数以选择所选父类别的子类别并按AJAX
显示它们。任何帮助将不胜感激!
这是我到目前为止拥有的php函数:
function make_model() {
$vehicle_make = $_REQUEST['id'];
global $wpdb;
$models = $wpdb->get_results($wpdb->prepare("SELECT * FROM car_models WHERE model_id='".$vehicle_make."'",13,'gargle'),ARRAY_A);
foreach($models as $model) {
echo '<option value="'.$model["model_id"].'">'.$model["model"].'</option>';
}
//echo $models;
die();
}
add_action('wp_ajax_make_model' , 'make_model');
add_action('wp_ajax_nopriv_make_model','make_model');
以下是输出选择下拉列表的html:
<div id="contents">
<form name="form" method="post" action="">
<label>Make: </label>
<select name="vehicle_make" class="vehicle_make">
<option>Select Make</option>
<?php
global $wpdb;
$vehicles = $wpdb->get_results($wpdb->prepare("SELECT * FROM car_makes",13,'gargle'),ARRAY_A);
foreach($vehicles as $vehicle) {
?>
<option value="<?php echo $vehicle["make_id"]; ?>"><?php echo $vehicle["make"]; ?></option>
<?php } ?>
</select>
<label>Model: </label>
<select name="vehicle_model" class="vehicle_model">
<option>Select Model</option>
</select>
</form>
</div>
,最后是ajax jQuery:
$('.vehicle_make').change(function(){
var vehicle_make = $(this).val();
$.ajax({
cache: false,
type: "POST",
url: ajaxurl,
data: {
action : 'make_model',
id : vehicle_make,
},
success: function(vehicle_model_data) {
console.log(vehicle_model_data);
$('.vehicle_model').html(vehicle_model_data);
}
});
});