A
A
alexiusgrey2022-03-17 15:39:47
WordPress
alexiusgrey, 2022-03-17 15:39:47

How to make select2 in the checkout instead of the usual one in the list of cities?

I just need a list of several cities, without regions. Of the methods from the Internet, this one worked for me to make the city field a select

add_filter( 'woocommerce_checkout_fields' , 'override_checkout_city_fields' );
function override_checkout_city_fields( $fields ) {
    // Define here in the array your desired cities (Here an example of cities)
    $option_cities = array(
         '' => __( 'Choose your city' ),
        'City1' => 'City1', 
        'City2' => 'City2',  
        );
    $fields['billing']['billing_city']['type'] = 'select';
    $fields['billing']['billing_city']['options'] = $option_cities;
    $fields['shipping']['shipping_city']['type'] = 'select';
    $fields['shipping']['shipping_city']['options'] = $option_cities;
    return $fields;
}


But this is a normal select, and I need select2 with a search, such as happens with select2 enhanced classes.
In theory, select2 is built into the kernel, unless it is specifically disabled. I didn’t disable it, but it didn’t help, and this snippet, which is popular on demand, which generally makes all selects as selects2, also doesn’t make it beautiful blue with search and with the necessary classes.
jQuery('select#billing_city').select2();
function enqueue_select2_jquery() {
    wp_register_style( 'select2css', '//cdnjs.cloudflare.com/ajax/libs/select2/3.4.8/select2.css', false, '1.0', 'all' );
    wp_register_script( 'select2', '//cdnjs.cloudflare.com/ajax/libs/select2/3.4.8/select2.js', array( 'jquery' ), '1.0', true );
    wp_enqueue_style( 'select2css' );
    wp_enqueue_script( 'select2' );
}
add_action( 'admin_enqueue_scripts', 'enqueue_select2_jquery' );
function select2jquery_inline() {
    ?>
<style type="text/css">
.select2-container {margin: 0 2px 0 2px;}
.tablenav.top #doaction, #doaction2, #post-query-submit {margin: 0px 4px 0 4px;}
</style>
<script type='text/javascript'>
jQuery(document).ready(function ($) {
    if( $( 'select' ).length > 0 ) {
        $( 'select' ).select2();
        $( document.body ).on( "click", function() {
             $( 'select' ).select2({
                  theme: "classic"
             });
          });
    }
});
</script>
    <?php
 }
add_action( 'admin_head', 'select2jquery_inline' );

I tried to connect hardcore right into the header link from the select2 site itself, just to believe it. How to do it correctly - which instruction from the documentation is not outdated or which method have you checked that is working?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question