Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add select2 js in wordpress admin side theme options

I have added Select2 js to provide search capabilities in my wordpress theme setting drop down options to add search -> http://nimb.ws/1QW6id

I have added the following code to my admin options file:

<?php if(is_admin()) { ?>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>

<script type="text/javascript">
  $(document).ready(function($) {
    $('.option-tree-ui-select').select2();
});
</script>

<?php } ?>

On the admin side this works, but the code conflicts with the admin side media menu. The media menu continuously loads and does not allow the uploading of new images. When I remove the new code, the media functionality begins to work appropriately.

Any ideas on how to fix this?

like image 858
Ketan Avatar asked Jan 02 '23 19:01

Ketan


1 Answers

Use wp_enqueue_script function for including scripts. Also remove your jquery call. Use dependencies.

See an example

Place this code in functions.php of your theme or in main plugin file:

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

This action will include select2 libraries and jquery. Third parameter of wp_register_script told WordPress that for this script working fine should be included jquery core. See more details on developers portal. If set 3rd param to array('jquery') jquery core will be included before your select2 plugin automatically.

Than in your page, header, scrtip file (where you wanna) place JS with call select2 plugin:

<script type="text/javascript">
  $(document).ready(function($) {
      $('.option-tree-ui-select').select2();
  });
</script>
like image 128
Maxim Sarandi Avatar answered Jan 05 '23 16:01

Maxim Sarandi