【问题标题】:Dynamic Select Dropdown Wordpress By advanced custom field动态选择下拉 Wordpress 按高级自定义字段
【发布时间】:2016-04-13 17:15:18
【问题描述】:

这是我的多重下拉代码。

我有两个下拉菜单,一个用于城市,另一个用于区域。

所以当有人选择一个城市时,区域下拉菜单应该会自动填充。

这是网址

http://ctclick.com/category/

<?  

 $field_key = "field_570e68df39304"; 
 $field = get_field_object($field_key);


 if( $field == 'pune' )

    {  
        $field_key = "field_570e68df39304"; 
        $field = get_field_object($field_key);
            if( $field )
                {    
                    echo '<select name="city" class="form-control" id="city">';        
                    foreach( $field['choices'] as $k => $v )        
                        {
                            echo '<option value="' . $k . '">' . $v . '</option>';        
                        }    
                            echo '</select>';
                }
    }

elseif ( $field == 'akola' )
    {
        $field_key = "field_570e691b39305"; 
        $field = get_field_object($field_key);
        if( $field )
            {    
                echo '<select name="city" class="form-control" id="city">';        
                    foreach( $field['choices'] as $k => $v )        
                        {            
                            echo '<option value="' . $k . '">' . $v . '</option>';        
                        }    
                            echo '</select>';
            }   
    }
else
{
    ?>
    <select class="form-control">
    <option>Select Area</option>
    </select>
    <?
}

 ?>

【问题讨论】:

  • 您的问题是...?
  • 请尊重这里试图帮助您的用户,并努力重新格式化您的代码
  • 我已重新格式化...请立即检查

标签: php wordpress advanced-custom-fields


【解决方案1】:

在这种情况下,您可能必须在代码中使用一些 ajax,以便当您更改第一个下拉菜单的值时,它会触发 ajax 调用。要实现这一点,您必须包含一些像这样的 javascript

$('#city_dropdown').change(function() {
    jQuery.ajax({
        url: "/wp-admin/admin-ajax.php",
        type: 'POST',
        data: {
            action: 'get_city_areas',
            city_id: $(this).val(),            
        },
        dataType: 'html',
        success: function (result) {
            $('#area-dropdown').html(result)
        },
        error: function (errorThrown) {
            console.log(errorThrown);
        }
    })
});

发生的情况是,当您的城市下拉列表发生更改时,它会触发 Ajax 请求以获取所有相关区域。 Wordpress 中的 Ajax 是通过 admin-ajax 系统完成的。你可以在这里阅读更多内容:https://codex.wordpress.org/AJAX_in_Plugins

在您的functions.php文件中,您可以添加以下内容来注册一个Ajax调用来检索城市区域

add_action('wp_ajax_get_city_areas', 'handle_get_city_areas');
add_action('wp_ajax_nopriv_get_city_areas', 'handle_get_city_areas');
/**
 * Handle the list of areas
 */
function handle_get_city_areas(){
    $city_id = $_POST['city_id'];
    //Using the city ID, retrieve the related areas
    //and then echo the new select menu
}

这应该可以帮助您获得所需的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 2012-08-10
    • 2015-01-21
    • 2017-05-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-25
    相关资源
    最近更新 更多