2017-08-06 80 views
0

我使用Woocommerce並編輯了城鎮結算表單,其中包含需要用戶選擇的500個城鎮和城市的下拉菜單。我如何實現搜索框,以便他們能夠搜索他們的城鎮?將搜索框添加到下拉式Wordpress

基本上,如何創建這樣的事情: Example

此: example

我定製的那場在Woocommerce,使用下面的代碼

add_filter('woocommerce_default_address_fields' , 'customize_checkout_city_field'); 
function customize_checkout_city_field($address_fields) { 

    // Set HERE the cities (one line by city) 
    $towns_cities_arr = array(
     '0' => __('Select your city', 'my_theme_slug'), 
     'paris' => 'Paris', 
     'versailles' => 'Versailles', 
     'cannes' => 'Cannes', 
    ); 

    // Customizing 'billing_city' field 
    $address_fields['city']['type'] = 'select'; 
    $address_fields['city']['class'] = array('form-row-last', 'my-custom-class'); // your class here 
    $address_fields['city']['label'] = __('Town/city', 'my_theme_slug'); 
    $address_fields['city']['options'] = $towns_cities_arr; 


    // Returning Checkout customized fields 
    return $address_fields; 

} 
+0

您有任何示例代碼供我們查看嗎? –

+0

@CodeApprentice添加了生成該表單域的相關代碼 – Jonathan

回答

1

這您要使用的插件是Select2 https://select2.github.io/examples.html

您已將您的字段上的自定義類稱爲我的自定義類

您只需導入select2庫。你可以在你的主題functions.php中做到這一點。

function mytheme_enqueue_custom_scripts() { 

    wp_enqueue_style('select2-css', 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css'); 

    wp_enqueue_script('select2-js', 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js'); 

} 
add_action('wp_enqueue_scripts', 'mytheme_enqueue_custom_scripts'); 

然後添加一些jQuery來初始化它。

<script type="text/javascript"> 

    jQuery(document).ready(function($) { 
     $(".my-custom-class").select2(); 
    }); 

</script> 
+1

Woocommerce似乎已經包含了select2,我相信這就是他們用於Country域的內容。令人費解的棘手部分是讓類被添加到正確的元素(仍然不知道什麼是正確的元素),上面添加了正確的類,但它沒有使下拉菜單可搜索,我最終做了什麼只是簡單地將類設置爲'select'(在jquery腳本中),它已經由woocommerce在下拉菜單中設置。這樣做對我有效。 – Jonathan