<div class="container p-3">
	<h2>Select2 and the WordPress REST API</h2>

	<form>
		<div class="form-group">
			<label for="test">Post</label>

			<select id="test" class="form-control pronamic-wp-posts-example"></select>
		</div>
	</form>
</div>
jQuery( document ).ready( function( $ ) {
	$( '.pronamic-wp-posts-example' ).select2( {
		allowClear: true,
		minimumInputLength: 2,
		ajax: {
			url: 'https://demo.wp-api.org/wp-json/wp/v2/categories',
			dataType: 'json',
			data: function ( params ) {
				return {
					search: params.term
				};
			},
			processResults: function( data ) {
				return {
					results: jQuery.map( data, function( obj ) {
						return { id: obj.id, text: obj.name };
					} )
				}
			}
		}
	} );
} );
Run Pen

External CSS

  1. https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap.css
  2. https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.1/css/select2.css

External JavaScript

  1. https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js
  2. https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/js/bootstrap.min.js
  3. https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.1/js/select2.full.js