【WordPress】管理画面にメディア選択欄を追加する

add_menu_page() で管理画面に独自メニューページを作ったり、add_meta_box で投稿管理画面に独自メタボックスを作ったりした場合に、そこにメディア選択欄(メディアライブラリにアクセスするためのボタン)を追加する方法についてまとめます。
完成イメージは以下のような感じです。

まずは functions.php を使って、管理画面に以下のような HTML を追加します。
<?php
//前略
wp_enqueue_media();
?>
<!-- 中略 -->
<table class="form-table" role="presentation">
<tr>
<th scope="row">画像を選択</th>
<td>
<input type="text" name="image_url" id="image_url" class="regular-text" value="<?php echo /*メタデータの取得を記載*/ ?>" readonly>
<p>
<button type="button" name="image_select" id="image_select" class="button media-button select-mode-toggle-button">画像を選択</button>
<button type="button" name="image_delete" id="image_delete" class="button media-button select-mode-toggle-button">画像を削除</button>
</p>
</td>
</tr>
</table>
<!-- 中略 -->
<?php
// 後略
?>
ここで wp_enqueue_media() は、Wordpressのメディアアップロードやメディアライブラリに関連するスクリプトやスタイルシートを読み込むために使用する関数です。
次に JavaScript で、各ボタン要素にクリックイベントを付加します。
jQuery(document).ready(function(){
function createCustomMedia(){
var media = wp.media({
title: 'メディアの選択またはアップロード',
library: {type: 'image'},
button: {text: '選択'},
multiple: false
});
return media;
}
var customMedia;
jQuery('#image_select').click(function(event){
event.preventDefault();
if(customMedia){
customMedia.open();
return;
}
customMedia = createCustomMedia();
customMedia.on('select', function(){
var attachment = customMedia.state().get('selection').first().toJSON();
jQuery('#image_url').val(attachment.url);
});
customMedia.open();
});
jQuery('#image_delete').click(function(event){
jQuery('#image_url').val('');
});
});
wp.media のパラメータを紹介しておきます。
- title:メディア選択欄の表示タイトル
- library:メディアの種類。image、audio、video、library(全種)など。
- button:メディア選択欄のボタンのラベル
- multiple:複数選択可能(true)か否(false)か
あとは admin_print_footer_scripts フックなどで、該当管理画面のフッターに、上記の作成した JavaScript を読み込ませるようにしたら完了です。以上テーマ開発者向けですが、比較的簡単に実装できるので試してみてください。
ちょっと宣伝
当サイトは WordPress 自作テーマを使った海外旅ブログ/YouTube まとめサイトとなっています。トップページに地図がありますが、地名を押すと画像が開き、画像を押すと関連記事一覧(クリック数順)が開きます。記事数が多い国ほど赤く、地名もその国で記事が多い都市の文字が大きくなるようにしています。ぜひ覗いてみてください。
当サイトで海外旅ブログを執筆することも可能です(もちろん無料です)! また既にブログをお持ちの方も、当サイトからリンクを貼ることができるようになっています。パントレ開発部までお気軽にお問い合わせください。
パントレ開発部