WordPress カスタム設定画面でメディアアップローダーから画像を選択・アップロードする機能を実装する

何を言ってるのか分からねーと思うが。 要するに、プラグインを作ったりする時に、設定画面内の項目でメディアライブラリの画像を選択できるようにしたい、ということです。

これをやりたい

自作プラグインの設定ページで、こういう↓フォームを作って、

ボタン押したらメディアライブラリが立ち上がって、

選択したらその画像のURLなりIDなりを取得したい。

実装

プラグインや設定ページの基本的な作り方は割愛します。そちらの方が長くなるので。

多言語化の記述なども、サンプルコードの主旨を分かりやすくするため省略します。

設定画面のHTML

設定画面側にはこんなHTMLを用意します。ただし、$value や inputのname属性などはプラグインの仕様に合せて変更してください。

<?php
$value = isset($this->options['image_url']) ? esc_html($this->options['image_url']) : '';
?>
<div class="my-uploader">
  <input type="text" class="my-uploader__url widefat" name="<?php echo self::option_name; ?>[image_url]" value="<?php echo $value; ?>">
  <p>
    <button class="my-uploader__select button">メディアライブラリから選択</button>
    <button class="my-uploader__clear button">画像をクリア</button>
  </p>
  <p><img class="my-uploader__image" src="<?php echo $value; ?>" style="width: 150px; height: auto;"></p>
</div>

管理画面で読み込ませるJavaScript

WordPressメディアアップローダーAPIなるものが用意されていますので、それを利用します。

JavaScript版

let $uploader = document.getElementsByClassName('my-uploader')

Array.from($uploader).forEach( (item) => {
  const $url = item.querySelector('.my-uploader__url')
  const $image = item.querySelector('.my-uploader__image')
  const $select = item.querySelector('.my-uploader__select')
  const $clear = item.querySelector('.my-uploader__clear')
  let uploader

  $select.addEventListener('click', (e) => {
    e.preventDefault()

    if (uploader) {
      uploader.open()
      return
    }

    // メディアアップローダーのインスタンス
    uploader = wp.media({
      title: 'メディアの選択またはアップロード',
      library: {
        type: 'image'
      },
      button: {
        text: '選択'
      },
      multiple: false
    })

    uploader.on('select', () => {
      const images = uploader.state().get('selection')

      // dataに選択した画像の情報が入ってる
      images.forEach( (data) => {
        const url = data.attributes.url
        $url.value = url
        $image.setAttribute('src', url)
      })
    })

    uploader.open()
  })

  $clear.addEventListener('click', (e) => {
    e.preventDefault()
    $url.value = ''
    $image.setAttribute('src', '')
  })
})

jQuery版

(function ($) {
  const $uploader = $('.my-uploader')


  $uploader.each(function (i, elem) {
    const $url = $(elem).find('.my-uploader__url')
    const $image = $(elem).find('.my-uploader__image')
    const $select = $(elem).find('.my-uploader__select')
    const $clear = $(elem).find('.my-uploader__clear')
    let uploader

    $select.on('click', function (e) {
      e.preventDefault()

      if (uploader) {
        uploader.open()
        return
      }

      // メディアアップローダーのインスタンス
      uploader = wp.media({
        title: 'Select Image',

        library: {
          type: 'image'
        },

        button: {
          text: 'Select Image'
        },

        multiple: false
      })

      uploader.on('select', function () {
        const images = uploader.state().get('selection')

        // dataに選択した画像の情報が入ってる
        images.each(function (data) {
          const url = data.attributes.url
          $url.val(url)
          $image.attr('src', url)
        })
      })

      uploader.open()
    })

    $clear.on('click', function (e) {
      e.preventDefault()
      $url.val('')
      $image.attr('src', '')
    })
  })
})(jQuery)

ちょっとした解説

サンプルではフルサイズのURLを取得していますが、他を取得したい場合。

// ID
data.id
// サムネイルサイズのURL
data.attributes.sizes.thumbnail.url

// その他を知りたい場合は
console.log(data)

なお、設定画面で、最初imgタグのsrcが空になってますが、設定画面なので細かいことは気にしなくてOK。