我正在尝试使用元数据箱在wordpress中存储逗号分隔的附件ID字符串.
我有MetaBox工作正常,但我试图让wp.media叠加打开方式允许用户选择多个图像,然后拖放它们,然后点击“选择”按钮,它将ID字符串放入元数据箱中.
请不要建议插件.我知道那里有很多它们,但是我将它构建成一个主题,并且想要最少的代码.
JS& PHP我有这个:
jQuery('.custom-post-gallery').on( 'click',function(e){
e.preventDefault();
var image_frame;
if(image_frame){
image_frame.open();
}
// Define image_frame as wp.media object
image_frame = wp.media({
title: 'Select gallery Images',library : {
type : 'image'
},multiple: true
});
image_frame.states.add([
new wp.media.controller.Library({
id: 'post-gallery',title: 'Select Images for the Post gallery',priority: 20,toolbar: 'main-gallery',filterable: 'uploaded',library: wp.media.query( image_frame.options.library ),multiple: image_frame.options.multiple ? 'reset' : false,editable: true,allowLocalEdits: true,displaySettings: true,displayUserSettings: true
});
]);
image_frame.open();
});
<?PHP
$Meta_key = 'custom_post_gallery';
$image_ids = get_post_meta( $post->ID,$Meta_key,true );
?>
<input class="custom-post-gallery" name="<?PHP echo $Meta_key; ?>" type="text" value="<?PHP echo $image_ids; ?>"/>
此叠加层仅显示用于选择一个图像的UI,或者如果按住控制键,则选择多个图像,但没有拖放顺序等.我能以某种方式在“图库”模式下打开它吗?并为其提供用于当前所选图像的ID?
谢谢!
解决方法
如果我说得对,你有一个文本字段,点击打开媒体窗口,你想在点击选择按钮时将所选图像的id插入字段值(id用逗号分隔).
如果是这样,那么这就是我修改的内容:
如果是这样,那么这就是我修改的内容:
固定:
由于分号错误(它在一个不能有分号的数组中)
displayUserSettings: true }); // --> here
改性:
需要在此范围之外设置image_frame变量,并在重新打开操作后返回
var image_frame; // --> outside the scope
if(image_frame){
image_frame.open();
// --> add return
}
加法:
包装JS并将jQuery注入$scope作为范围,现在我们可以使用$sign代替jQuery并防止与其他JS脚本冲突:
(function($){
...
})(jQuery);
将文本字段对象设置为$that变量,以便我们在更深的范围内使用它
var $that = $(this);
添加选择操作,并将选中的图像ID以逗号分隔,插入字段值:
image_frame.on( 'select',function() {
var ids = '',attachments_arr = [];
// Get media attachment details from the frame state
attachments_arr = image_frame.state().get('selection').toJSON();
$(attachments_arr).each(function(e){
sep = ( e != ( attachments_arr.length - 1 ) ) ? ',' : '';
ids += $(this)[0].id + sep;
});
$that.val(ids);
});
全部一起:
只是JS部分,它被修改:
(function($){
var image_frame;
$('.custom-post-gallery').on( 'click',function(e){
e.preventDefault();
// If the media frame already exists,reopen it.
if (image_frame){
image_frame.open();
return;
}
var $that = $(this);
// Define image_frame as wp.media object
image_frame = wp.media({
title: 'Select gallery Images',library : {
type : 'image'
},multiple: true
});
image_frame.states.add([
new wp.media.controller.Library({
id: 'post-gallery',displayUserSettings: true
})
]);
image_frame.open();
image_frame.on( 'select',' : '';
ids += $(this)[0].id + sep;
});
$that.val(ids);
});
});
})(jQuery);
这对我有用,告诉我你是否有任何问题.