Using Chosen.js On Conditional Checkout Field Select Menus

The Conditional Checkout Fields plugin comes with the Chosen.js library already installed. This is what allows you to search for products or categories in the conditional field settings page.

You might have a conditional select menu field on your checkout page with a large number of options where you want customers to be able to search for their response.

In that case, you can reuse the Chosen.js library that is already installed in the Conditional Checkout Fields plugin.

Add the following code to your theme's functions.php or a custom plugin file.

add_action( 'wp_enqueue_scripts', 'checkout_chosen_select_menus' );
function checkout_chosen_select_menus(){
	// Only load the code on the checkout page to avoid extra files being loaded elsewhere on the site.
	if( is_checkout() ){
		// Use the Chosen jQuery from Conditional Checkout Fields plugin.
		wp_register_script( 'cwcfp_chosen_core_js_checkout', CWCFP_PLUGIN_URL . '/includes/js/chosen_v1.6.2/chosen.jquery.min.js', array( 'jquery' ), '1.0', false );
		wp_enqueue_script( 'cwcfp_chosen_core_js_checkout' );
		// Create a new script that will let us target the select field with a certain class on the checkout page.
		wp_register_script( 'cwcfp_searchable_checkout', get_template_directory_uri() . '/searchable-products.js', array( 'jquery' ), '1.0', false );
		wp_enqueue_script( 'cwcfp_searchable_checkout' );
		// Add the Chosen styles to make it pretty.
		wp_register_style( 'cwcfp_chosen_core_css_checkout', CWCFP_PLUGIN_URL . '/includes/js/chosen_v1.6.2/chosen.min.css' );
		wp_enqueue_style( 'cwcfp_chosen_core_css_checkout' );

You will also need to add the searchable-products.js file to your theme's root directory. You can put it somewhere else, but you will have to change the cwcfp_searchable_checkout reference to point to wherever you are saving this file.

In the searchable-products.js file you will add the following code.

jQuery(document).ready(function () {
	jQuery("p.cwcfp-searchable select").chosen({
		disable_search_threshold: 1,
		allow_single_deselect: true,
		disable_search: false,
		no_results_text: "Oops, nothing found!",
		width: "100%"

Finally, you will need to add a class in the conditional select menu field's settings. That class should be cwcfp-searchable, which will make this field match the second line in the jQuery code above.

The end result will look something like this: