Add Chosen in Wordpress frontend

Viewed 919

Good morning.

I would like to add Chosen style in Wordpress Frontend Select. I've enqueue CSS and JS in a specific page:

function enqueue_chosen() {
  if ( is_page( 'my-page' ) ) {
    wp_enqueue_style( 'chosen_css', plugins_url('chosen/chosen.css') );
        wp_enqueue_script( 'chosen_js', plugins_url('chosen/chosen.jquery.js'), array('jquery'), '', true );
  }
}
add_action( 'wp_enqueue_scripts', 'enqueue_chosen' );

File is enqueued correctly. Now how I can apply chosen style in my select box?

Thanks for help!

2 Answers

Below are three steps to turn any select box in your Wordpress page into a Chosen type select box.

  1. enqueue the chosen library in your themes functions.php

function my_enqueue_files() {
  wp_enqueue_style( 'chosen_styles', 'https://harvesthq.github.io/chosen/chosen.css', false );
  wp_enqueue_script( 'jquery' );
  wp_enqueue_script( 'chosen_js', 'https://harvesthq.github.io/chosen/chosen.jquery.js', array('jquery'), null, true );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_files' );

  1. put the jQuery(document).ready(function...) in one script at the bottom of the page and then another script calling the jQuery(document).ready(function...).
    Note: This must be in two scripts. the snippet:

<script>
    jQuery(document).ready(function () {
      jQuery(".chosen-select").chosen({
          search_contains: true,
          no_results_text: "Nothing found for: ",
          width: "100%",
      });
    });
    $('select').chosen({

    allow_single_deselect: true
    });
    </script>`
    `<script>
    jQuery(document).ready(function(){
        jQuery(".chosen").chosen();
    });
    </script>
  1. Use the class='chosen' on the particular select.

for select with one selection:


`<select class="chosen" style="width:200px;">
    <option>Choose...</option>
    <option>Option 1</option>
        .....

for select with multiple selections:

<select class="chosen" multiple="true" style="width:400px;">
    <option>Choose...</option>
       ....

Hope it helps.

Related