WordPress中的依赖下拉列表 [英] Dependent dropdown in wordpress

查看:53
本文介绍了WordPress中的依赖下拉列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用自定义代码在WordPress中创建成本估算表,并且我是PHP,AJAX和MYSQL的初学者,因此我需要以下查询的帮助.

基本上需要为Car Make和Car Model创建一个依赖下拉列表,因此我创建了一个dab表调用 wp_cost_estimation ,该调用具有 id make make_id model .请参见下图.

因此,如果用户在下一个下拉列表中选择Acura,则应该显示所有Acura模型,而无需重复.我尝试了下面的代码.请纠正我错了的地方.

cost_estimation_template.php

 < select占位符="Select Make"name ="make"id ="make"><选项已禁用="selected =""-选择Make-</option><?php包括get_theme_file_path('/data.php');$ makes = loadMake();foreach($ makes为$ make){echo< option id ='".$ make ['id'].'value ='" .. $ make ['id']."''>" .. $ make ['make']."</option>";}?></select><选择占位符=选择模型";名称=模型"id ="model"><选项已禁用="selected =" ---选择模型-</option></select> 

data.php

  if(isset($ _ POST ['aid'])){$ db =新的DbConnect;$ conn = $ db-> connect();$ stmt = $ conn-> prepare("从wp_cost_estimation处选择模型名称WHERE make_id =.$ _POST ['aid'] GROUP BY model_name);$ stmt-> execute();$ models = $ stmt-> fetchAll(PDO :: FETCH_ASSOC);回声json_encode($ models);}函数loadMake(){$ db =新的DbConnect;$ conn = $ db-> connect();$ stmt = $ conn-> prepare("SELECT MIN(id)AS id,make FROM wp_cost_estimation GROUP BY make");$ stmt-> execute();$ make = $ stmt-> fetchAll(PDO :: FETCH_ASSOC);返回$ make;} 

AJAX代码:

 < script type ="text/javascript">$(document).ready(function(){$(#make").change(function(){var aid = $(#make").val();$ .ajax({网址:<?php echo get_theme_file_path('/data.php');?>',方法:发布",数据:"aid =" +辅助}).done(函数(模型){console.log(model);模型= JSON.parse(model);$('#model').empty();model.forEach(function(models){$('#model').append('< option>'+ models.model_name +'</option>')})})})})</script> 

请帮帮我.

解决方案

如果您使用的是WordPress,则肯定要给

I am trying to create a cost estimation form in WordPress using custom code and I am a beginner in PHP, AJAX, and MYSQL so I need help in the below query.

Basically need to create a dependent dropdown for Car Make and Car Model so I have created one dab table call wp_cost_estimation which has id, make, make_id, model. See the below image.

So if the user selects Acura in the next drop down it should show all the Acura models without repetition. I tried the below code. Please correct me where I am wrong.

cost_estimation_template.php

 <select placeholder="Select Make" name="make" id="make">
              <option disabled="" selected="">--Select Make--</option>
              <?php

                    include get_theme_file_path( '/data.php' );
                    $makes = loadMake();

                    foreach ($makes as $make) {
                                    echo "<option id='".$make['id']."' value='".$make['id']."'>".$make['make']."</option>";
                                }
              ?>
            </select>

  <select placeholder="Select Model" name="model" id="model">
              <option disabled="" selected="">--Select Model--</option>

            </select>

data.php

 if(isset($_POST['aid'])) {
    $db = new DbConnect;
    $conn = $db->connect();
    $stmt = $conn->prepare("SELECT model_name FROM wp_cost_estimation WHERE make_id = " . $_POST['aid'] GROUP BY model_name);
    $stmt->execute();
    $models = $stmt->fetchAll(PDO::FETCH_ASSOC);
    echo json_encode($models);
}

 
  function loadMake() {
    $db = new DbConnect;
    $conn = $db->connect();

    $stmt = $conn->prepare("SELECT MIN(id) AS id, make FROM wp_cost_estimation GROUP BY make");
    $stmt->execute();
    $make = $stmt->fetchAll(PDO::FETCH_ASSOC);
    return $make;
}

AJAX Code:

<script type="text/javascript">
    $(document).ready(function(){
        $("#make").change(function(){
            var aid = $("#make").val();
            $.ajax({
                url: '<?php echo get_theme_file_path('/data.php'); ?>',
                method: 'post',
                data: 'aid=' + aid
            }).done(function(model){
                console.log(model);
                model = JSON.parse(model);
                $('#model').empty();
                model.forEach(function(models){
                $('#model').append('<option>' + models.model_name + '</option>')
                })
            })
        })
    })
</script>  

Please help me out.

解决方案

If you're using WordPress, you'll definitely want to give the AJAX in Plugins and J.A.jQ Codex a thorough read, you're not really using any of the benefits of WordPress if your existing code.

The two biggest things you'd want to take advantage of here are the wp_ajax_{$action}() hook and the $wpdb class.

The wp_ajax_ (and wp_ajax_nopriv_) hooks allow you to easily run functions with specific actions, and the $wpdb class handles the vast majority (read: all) of the database connection and interactions that you'll need. And you can drop almost all of this in your functions.php file (or a plugin file, or Must Use Plugin file)

I've taken the liberty of setting up a working example here: https://xhynk.com/content-mask/65517584-answer/

Here's what the functions.php file looks like:

function loadMake(){
    global $wpdb;
    return $wpdb->get_results( "SELECT MIN(id) AS id, make FROM cm_test_make_model GROUP BY make" );
}

add_action( 'wp_enqueue_scripts', function(){
    wp_enqueue_script( '65517584', get_stylesheet_directory_uri() . '/assets/scripts/65517584.js', [], filemtime(get_stylesheet_directory() . '/assets/scripts/65517584.js'), true );

    $localize = array( 'ajax_url' => admin_url( 'admin-ajax.php' ) );
    wp_localize_script( '65517584', 'ajax_object', $localize );
});

add_action( 'wp_ajax_load_models', 'load_models' );
add_action( 'wp_ajax_nopriv_load_models', 'load_models' );
function load_models(){
    if( isset($_POST['aid']) ){
        global $wpdb;
        
        $sql = "SELECT model_name FROM cm_test_make_model WHERE make_id = %d GROUP BY model_name";
        $results = $wpdb->get_results( $wpdb->prepare( $sql, array( absint($_POST['aid']) ) ) );

        wp_send_json( $results, 200 );
    } else {
        wp_send_json( array('message', 'aid is required'), 400 );
    }
}

You'll note the loadMake() function uses $wpdb to make the simple query (I also changed the table name to fit mine)

It's also enqueuing the JavaScript file, and localizes it with wp_localize_script() to pass the appropriate AJAX URL to it (this is also how you can pass along other data from PHP to your JS handler).

The last part uses the wp_ajax_ hooks to run the load_models function, and uses $wpdb's helper functions to prepare the statement, and wp_send_json to convert it to JSON, print it out, and then die. (IT IS VERY IMPORTANT TO KILL THE REQUEST WITH DIE/EXIT AFTER RUNNING A FUNCTION VIA AJAX. If you echo out the json manually, you'll need to call die or exit after.)

Below is the enqueued JavaScript file (note, I enqueued this relative to my theme, you may need to change the URL that's enqueued above if yours is in a different location:

jQuery(document).ready(function($){
    $("#make").change(function(){
        var aid = $("#make").val();
        $.ajax({
            url: ajax_object.ajax_url + '?action=load_models',
            method: 'post',
            data: 'aid=' + aid
        }).done(function(models){
            $('#model').empty();
            models.forEach(function(model){
                console.log( model );
                $('#model').append('<option>' + model.model_name + '</option>');
            });
        });
    });
});

You can see the URL is using the localized variable we passed along.

Lastly, I made a simple Page Template that has the selects on it. Note that wp_enqueue_scripts requires wp_head() on the page, and if using the $in_footer option of wp_enqueue_script() you'll need wp_footer() as well:

<?php wp_head(); ?>
<select placeholder="Select Make" name="make" id="make">
    <option disabled="" selected="">--Select Make--</option>
    <?php
        $makes = loadMake();
        foreach( $makes as $make ){
            printf( '<option id="%d" value="%d">%s</option>', $make->id, $make->id, $make->make );
        }
    ?>
</select>

<select placeholder="Select Model" name="model" id="model">
    <option disabled="" selected="">--Select Model--</option>
</select>
<?php wp_footer(); ?>

A bit long-winded (sorry!) but you'll really want to make use of WordPress' ecosystem if you're going to be using it. And again, here's the link to the working example using the code above:

这篇关于WordPress中的依赖下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆