Slim Select with WordPress.org API

Slim select is an excellent library for select field type. There are rich API to implement many features. Code below is a example of selecting the the WordPress themes from WordPress.org with its API. https://slimselectjs.com/options

Thumbnail

// js
import SlimSelect from "slim-select";

/**
   * 佈景主題下拉選單
   */
  new SlimSelect({
    select: '#selectTheme',
    searchingText: 'Searching...',
    searchText: 'No results, you can click right button to add new one if you want!',
    placeholder: 'Choose one',
    ajax: function (search, callback) {
      if (search.length < 3) {
        callback('Need 3 characters')
        return
      }

      // Perform your own ajax request here
      fetch('https://api.wordpress.org/themes/info/1.1/?action=query_themes&request[search]='+ search +'&request[per_page]=99')
        .then(function (response) {
          return response.json()
        })
        .then(function (json) {
          let data = []
          for (let i = 0; i < json.themes.length; i++) {
            data.push({ value: json.themes[i].slug, text: json.themes[i].name })
          }
          callback(data)
        })
        .catch(function (error) {
          callback(error)
        })
        
    },
    addable: function (value) {
      // return false or null if you do not want to allow value to be submitted
      if (value === 'fuck') { return false }

      // Return the value string
      return value // Optional - value alteration // ex: value.toLowerCase()
    }
  });

Tags: