Skip to content

Instantly share code, notes, and snippets.

@shangdev
Created December 13, 2017 09:52
Show Gist options
  • Save shangdev/b8b83bc7b1bdda1ec19bee7599a25a49 to your computer and use it in GitHub Desktop.
Save shangdev/b8b83bc7b1bdda1ec19bee7599a25a49 to your computer and use it in GitHub Desktop.
wordpress metabox 单图像设置
### HTML结构 ###
a:html内容(未选择)
<p class="hide-if-no-js set-check-media-image">
<a href="javascript:void(0);" onclick="jQuery.metaboxCheckMedia(this,'_case_cover')">
选择图像
</a >
</p>
b:html内容(已选择)
<p class="hide-if-no-js set-check-media-image">
<a href="javascript:void(0);" onclick="jQuery.metaboxCheckMedia(this,'_case_cover')">
<img src="">
</a >
</p>
<p class="hide-if-no-js set-check-media-desc">点击图片来修改或更新</p>
<p class="hide-if-no-js set-check-media-del"><a href="javascript:void(0);" onclick="jQuery.metaboxDelMedia(this)">移除图像</a></p>
### JS方法 ###
/**
* Meta box check media
*
* @param obj 当前点击对象
* @param target 需要改变的input值
*/
jQuery.metaboxCheckMedia = function (obj, target) {
var _this = jQuery(obj)
var upload_thickbox = wp.media({
title: '图像选择',
button: {
text: '选择'
},
multiple: false
}).on('select', function () {
// Remove old html
_this.parent().siblings('.set-check-media-desc').remove()
_this.parent().siblings('.set-check-media-del').remove()
_this.parent().siblings('.set-check-media-image').find('a').text('选择图像')
_this.parent().siblings('input').val('')
var attachment = upload_thickbox.state().get('selection').first().toJSON()
var html_img = '<img width="100%" height="auto" src="' + attachment.sizes.medium.url + '"/>'
var html_tip = '<p class="hide-if-no-js set-check-media-desc">点击图片来修改或更新</p>'
html_tip += '<p class="hide-if-no-js set-check-media-del"><a href="javascript:void(0);" onclick="jQuery.metaboxDelMedia(this)">移除图像</a></p>'
_this.html(html_img)
_this.parent().parent().append(html_tip)
$('#' + target).val(attachment.id)
}).open()
}
/**
* Delete meta box image
*
* @param obj 当前点击对象
*/
jQuery.metaboxDelMedia = function (obj) {
var _this = jQuery(obj)
_this.parent().siblings('.set-check-media-desc').remove();
_this.parent().siblings('.set-check-media-image').find('a').text('选择图像');
_this.parent().siblings('input').val('');
_this.parent().remove();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment