| 1 |
const $ = jQuery; |
| 2 |
|
| 3 |
function formatCourse( repo ) { |
| 4 |
if ( repo.loading ) { |
| 5 |
return repo.text; |
| 6 |
} |
| 7 |
const markup = "<div class='select2-result-course_title'>" + repo.id + ' - ' + repo.title.rendered + '</div>'; |
| 8 |
return markup; |
| 9 |
} |
| 10 |
|
| 11 |
function formatCourseSelection( repo ) { |
| 12 |
return repo.title.rendered || repo.text; |
| 13 |
} |
| 14 |
|
| 15 |
function autocompleteWidget( widget = null ) { |
| 16 |
const searchs = $( '.lp-widget_select_course' ); |
| 17 |
const wpRestUrl = searchs.data( 'rest-url' ); |
| 18 |
const postType = searchs.data( 'post_type' ) || 'lp_course'; |
| 19 |
|
| 20 |
searchs.select2( { |
| 21 |
ajax: { |
| 22 |
method: 'GET', |
| 23 |
url: wpRestUrl + 'wp/v2/' + postType, |
| 24 |
dataType: 'json', |
| 25 |
delay: 250, |
| 26 |
data( params ) { |
| 27 |
return { |
| 28 |
search: params.term, |
| 29 |
}; |
| 30 |
}, |
| 31 |
processResults( data, params ) { |
| 32 |
params.page = params.page || 1; |
| 33 |
|
| 34 |
return { |
| 35 |
results: data, |
| 36 |
}; |
| 37 |
}, |
| 38 |
cache: true, |
| 39 |
}, |
| 40 |
escapeMarkup( markup ) { |
| 41 |
return markup; |
| 42 |
}, |
| 43 |
minimumInputLength: 2, |
| 44 |
templateResult: formatCourse, // omitted for brevity, see the source of this page |
| 45 |
templateSelection: formatCourseSelection, // omitted for brevity, see the source of this page |
| 46 |
} ); |
| 47 |
} |
| 48 |
|
| 49 |
document.addEventListener( 'DOMContentLoaded', function( event ) { |
| 50 |
if ( document.querySelector( '#widgets-editor' ) ) { |
| 51 |
$( document ).on( 'widget-added', function( event, widget ) { |
| 52 |
autocompleteWidget( widget ); |
| 53 |
} ); |
| 54 |
} else { |
| 55 |
$( document ).on( 'learnpress/widgets/select', function() { |
| 56 |
autocompleteWidget(); |
| 57 |
} ); |
| 58 |
|
| 59 |
autocompleteWidget(); |
| 60 |
} |
| 61 |
} ); |
| 62 |
|