Support Forum
Support › Meta Box Builder › Custom field and select2Resolved
Hello, I need a select 2 custom field, is possible use select2 library in my own filds?
I have de next field, Please consider that field is in group and the group is clonable
add_action( 'init', function() {
if ( class_exists( 'RWMB_Field' ) ) {
class RWMB_Versiones_Field extends RWMB_Field {
public static function html( $meta, $field ) {
$html = '';
$html .= '<select name="' . $field['field_name'] . '" id ="' . $field['id'] . '" class="rwmb">';
foreach($GLOBALS['versiones'] as $key => $value){
$selected = ($value['vers_id']==$meta)?' selected':'';
$html .= '<option value="' . $value['vers_id'] . '"' . $selected . '>' . $value['vers_nombre'] . '</option>';
}
$html .= '</select>';
return $html;
}
}
}
} );
Hi,
You can enqueue the select2 library then apply the function select2()
to the selector with some Javascript code.
function enqueue_select2_jquery() {
wp_register_style( 'select2css', 'https://cdnjs.cloudflare.com/ajax/libs/select2/3.4.8/select2.css', false, '1.0', 'all' );
wp_register_script( 'select2', 'https://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' );
add_action( 'admin_footer', function() {
?>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('#field_id').select2();
});
</script>
<?php
} );
Follow this topic for more information https://stackoverflow.com/questions/48879027/how-to-add-select2-js-in-wordpress-admin-side-theme-options.
And please notice, the plugin Meta Box also enqueues the library select2 when display some fields select
(multiple => true), select_advanced
... so be careful when loading another select2 Javascript file might happen a conflict.