jquerywordpresswoocommercewoocommerce-theming

How to enque select2 on frontend correctly?


In checkout I need the dropdown of CITIES. I don't deed country and region fields, so they are unset at all. To make the city field as dropdown instead of text I used that code.

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;
}

It works for me. But I need not simple select, but select2. I thought it's already enabled in checkkout, but simply

jQuery('select#billing_city').select2();

doesn't work. I tried this famous snippet

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' );

It didn't help too. How to make my select blue with search option in correct way?


Solution

  • Since selectWoo which is a WooCommerce replacement for Select2 is already enqueued with WooCommerce, you can simply use wc_enqueue_js and call it.

    add_action( 'woocommerce_before_checkout_form', 'add_select2_to_city' );
    function add_select2_to_city(){
        wc_enqueue_js( "$('select#billing_city').selectWoo();");
    }
    

    Add this to your functions.php.