自动摘要
正在生成中……
add_filter('ajax_query_attachments_args', 'filter_watch_images_media_library');
// 添加过滤器函数
function filter_watch_images_media_library($query)
{
// 检查是否是媒体库查询请求
if (isset($_POST['action']) && $_POST['action'] === 'query-attachments') {
// 检查是否是从我们的上传按钮触发的
if (isset($_POST['query']['watch_db_upload'])) {
// 设置查询条件,只显示 watch-images 目录下的图片
$query['meta_query'] = array(
array(
'key' => '_wp_attached_file',
'value' => 'watch-images/',
'compare' => 'LIKE'
)
);
}
}
return $query;
}
js 的内容如下:
jQuery(document).ready(function($) {
// 图片上传
$('#upload_image_button').click(function(e) {
e.preventDefault();
var image_frame;
if (image_frame) {
image_frame.open();
return;
}
image_frame = wp.media({
title: '选择手表图片',
multiple: false,
library: {
type: 'image'
}
});
// 前端控制台监控查询请求
jQuery(document).ajaxSuccess(function(event, xhr, settings) {
if (settings.data.includes('action=query-attachments')) {
console.log('媒体库查询参数:', settings.data);
}
});
// 设置媒体库查询参数
image_frame.on('open', function() {
var selection = image_frame.state().get('library');
selection.props.set('query', true);
selection.props.set('watch_db_upload', true);
});
image_frame.open();
});
});
关键代码在这里
// 设置媒体库查询参数
image_frame.on('open', function() {
var selection = image_frame.state().get('library');
selection.props.set('query', true);
selection.props.set('watch_db_upload', true);
});
会向后端发送一个包含 watch_db_upload 的查询参数,后端收到后修改默认查询参数。
不过这样做之后有一个问题,就是新上传的文件无法显示在这个右侧的媒体库列表,暂时没有解决。