Files
wordpress-theme-aksrt/assets/admin/src/utils/media.js
T

41 lines
894 B
JavaScript

export function openMediaPicker(options = {}) {
const wpMedia = window.wp?.media
if (!wpMedia) {
throw new Error('当前后台未加载 WordPress 媒体库。')
}
const frame = wpMedia({
title: options.title || '选择图片',
button: {
text: options.buttonText || '使用此图片',
},
library: {
type: options.type || 'image',
},
multiple: false,
})
return new Promise((resolve, reject) => {
frame.on('select', () => {
const attachment = frame.state().get('selection').first()?.toJSON()
if (!attachment?.url) {
reject(new Error('未选择有效的媒体资源。'))
return
}
resolve(attachment)
})
frame.on('close', () => {
const hasSelection = frame.state().get('selection').length > 0
if (!hasSelection) {
resolve(null)
}
})
frame.open()
})
}