Enable select2 for wp_dropdown_categories dropdown in WooCommerce
I have revisited a bit your code as for example in shortcode functions the content should always be returned and not echoed.
I have renamed the shortcode to something better, shorter… and enabled select2 for both dropdowns.
The function code:
add_shortcode( 'new_search', 'new_filter_search_shortcode' );function new_filter_search_shortcode( $atts ) { extract( shortcode_atts( array( 'taxonomy' => 'product_cat', // Product category taxonomy (by default) ), $atts ) ); ob_start(); // Start buffering ?> <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" /> <form name="myform" method="GET" action="<?php echo esc_url(home_url('/')); ?>"> <?php if (class_exists('WooCommerce') ) { if(isset($_REQUEST[$taxonomy]) && ! empty($_REQUEST[$taxonomy])) { $optsetlect = esc_attr($_REQUEST[$taxonomy]); } else { $optsetlect = 0; } $class = 'cate-dropdown hidden-xs'; wp_dropdown_categories( array( 'show_option_all' => esc_html__( 'Make / Model', 'woocommerce' ), 'orderby' => 'name', 'child_of' => 142, 'hierarchical' => 1, 'echo' => 1, 'depth' => 2, 'show_count' => 1, 'value_field' => 'name', 'selected' => $optsetlect, 'taxonomy' => $taxonomy, 'name' => 'model', 'class' => $class, ) ); wp_dropdown_categories( array( 'show_option_all' => esc_html__( 'Year', 'woocommerce' ), 'orderby' => 'name', 'child_of' => 69, 'hierarchical' => 1, 'echo' => 1, 'depth' => 2, 'show_count' => 0, 'value_field' => 'slug', 'selected' => $optsetlect, 'taxonomy' => $taxonomy, 'name' => 'year', 'class' => $class, ) ); } $search_text = esc_html__('Search', 'woocommerce'); ?> <button type="submit" title="<?php echo $search_text; ?>" class="search-btn-bg"><span><?php echo $search_text;?></span></button> </form> <?php // Enable select2 for both dropdowns if (class_exists('WooCommerce') ) { ?> <script> jQuery(function($){ $('select#model').select2(); $('select#year').select2(); }); </script> <?php wp_enqueue_script( 'select2' ); } return ob_get_clean(); // return buffered content}
Code goes in functions.php file of your active child theme (or active theme). Tested and works.
USAGE: [new_search]
or echo do_shortcode('[new_search]');
(inside PHP code).