WordPressのカスタムメタボックスにカスタムフィールドを作成しています。テキストフィールド、テキストエリア、およびチェックボックスはすべて正常に動作しています。私はまた働いている画像ギャラリーの参照ボタンを含んでいた。特定の入力フィールドに画像アップロードURLのみを適用する
[参照]ボタンをクリックすると、WordPressメディアアップロード画面が表示され、その画像を選択すると入力値(画像サムネイル)が置き換えられます。
ここには、WordPressメタボックスの関連部分が設定されています。
function show_custom_fields_meta_box() {
global $post;
$meta = get_post_meta($post->ID, 'custom_fields', true); ?>
<input type="hidden" name="custom_meta_box_nonce" value="<?php echo wp_create_nonce(basename(__FILE__)); ?>">
<!-- image upload field -->
<p>
<label for="custom_fields[image]">Image Upload</label><br>
<input type="text" name="custom_fields[image]" id="custom_fields[image]" class="meta-image regular-text" value="<?php echo $meta['image']; ?>">
<input type="button" class="button image-upload" value="Choose or Upload an Image">
<div class="image-preview"><img src="<?php echo $meta['image']; ?>" style="max-width: 250px;"></div>
</p>
}
そして、ここでは、私はWordPressのメディアギャラリーを開いて、画像をアップロードするために使用しているjQueryの。
<script>
/*
* Attaches the image uploader to the input field
*/
jQuery(document).ready(function ($) {
// Instantiates the variable that holds the media library frame.
var meta_image_frame;
// Runs when the image button is clicked.
$('.image-upload').click(function (e) {
// Prevents the default action from occuring.
e.preventDefault();
var selected = $(this);
var meta_image = $('.meta-image');
// If the frame already exists, re-open it.
if (meta_image_frame) {
meta_image_frame.open();
return;
}
// Sets up the media library frame
meta_image_frame = wp.media.frames.meta_image_frame = wp.media({
title: meta_image.title,
button: {
text: meta_image.button
}
});
// Runs when an image is selected.
meta_image_frame.on('select', function() {
// Grabs the attachment selection and creates a JSON representation of the model.
var media_attachment = meta_image_frame.state().get('selection').first().toJSON();
// Sends the attachment URL to our custom image input field.
$('.meta-image').val(media_attachment.url);
var imgurl = $('.meta-image').val();
$(selected).prev().val(imgurl);
$(selected).closest('div').find('.image-preview').children('img').attr('src',imgurl);
});
// Opens the media library frame.
meta_image_frame.open();
});
});
</script>
は今、これはそのまま完全に正常に動作します。 input
ボタンのクラスは.image-upload
であり、input
テキストフィールドのクラスはmeta-image
です。
それはクラスですので、しかし、私は別のフィールド...(custom_fields[image2]
)
<p>
<label for="custom_fields[image2]">Image Upload</label><br>
<input type="text" name="custom_fields[image2]" id="custom_fields[image2]" class="meta-image regular-text" value="<?php echo $meta['image2']; ?>">
<input type="button" class="button image-upload" value="Choose or Upload an Image">
<div class="image-preview"><img src="<?php echo $meta['image2']; ?>" style="max-width: 250px;"></div>
</p>
を追加する場合はjQueryのは、参照ボタンとテキスト入力の両方に適用されます。私は正しいボタンとテキストの入力を得るために何らかの形の$(this)
を使用しなければならないと思っていますが、私の努力はこれまで無駄でした。
私は$(this).closest('.meta-image')
を試しましたが、うまくいかないようです。
ありがとうございました!