目前的情况是,您正在将选定的媒体项分配给以下行中的所有三个输入:
j(\'#preview-fav, #preview-grav, #preview-thumb\').val(attachment.url);
为了只将值传递给其中一个,需要更改该行以响应按钮中设置的某种标记。在下面的示例中,我设置了
data
javascript中引用的按钮中的属性。
因此,假设您有以下html:
<!-- upload buttons -->
<input type="button" class="upload-button" data-target="input_1" value="Upload button 1" />
<input type="button" class="upload-button" data-target="input_2" value="Upload button 2" />
<input type="button" class="upload-button" data-target="input_3" value="Upload button 3" />
<!-- inputs to receive the value -->
<input type="text" id="input_1" value="" />
<input type="text" id="input_2" value="" />
<input type="text" id="input_3" value="" />
现在可以在js中执行此操作:
jQuery(function($) {
$(document).ready(function () {
var mediaUploader;
// we can now use a single class name to reference all upload buttons
$(\'.wp-admin\').on(\'click\', \'.upload-button\', function(e) {
e.preventDefault();
// store the element that was clicked for use later
trigger = $(this);
if( mediaUploader ){
mediaUploader.open();
return;
}
mediaUploader = wp.media.frames.file_frame = wp.media({
title: \'Upload\',
button: {
text: \'Upload\'
},
multiple: false
});
mediaUploader.on(\'select\', function() {
attachment = mediaUploader.state().get(\'selection\').first().toJSON();
// we\'re replacing this line:
//$(\'#preview-fav, #preview-grav, #preview-thumb\').val(attachment.url);
// assign the value of attachment to an input based on the data-target value
// of the button that was clicked to launch the media browser
$(\'#\' + trigger.data(\'target\') ).val(attachment.url);
$(\'.favicon-preview, .gravatar-preview, .thumbnail-preview\').css(\'background\',\'url(\' + attachment.url + \')\');
});
mediaUploader.open();
});
});
});
更新基于粘贴的代码,您可以通过以下方式提高效率:
function sweetlola_images(){
$imgs = array(
\'gravatar\' => \'img_1\',
\'thumbnail\' => \'img_2\',
);
foreach( $imgs as $name => $id ){
// get the image
$url = esc_attr( get_option( $name ) );
// if there isn\'t one, set $gravatar as empty string
$url = $url ? $url : \'\';
//upload button
echo \'<input type="button" data-target="\' . $id . \'" value="Upload" class="button button-secondary upload-button" />\';
//input text field
echo \'<input type="text" id="\' . $id . \'" name="\' . $name . \'" value="\' . $url . \'" />\';
if( empty( $url ) ){ //if the value is empty this will show a just the upload button
echo \'<input type="button" value="Remove" data-remove_target="\' . $id . \'" class="button button-secondary" />\';
}
// note
echo \'<p><i>Idem.<br />Resolução: 89px X 89px</i></p>\';
}
}
将三种图像类型放入
$imgs
数组,并使用单个函数生成它们。