WordPress媒体上传器:自定义标签上传后不刷新问题求助
解决WordPress媒体上传器自定义标签不自动刷新的问题
我之前也踩过这个坑!WordPress媒体上传器的弹窗默认只认「媒体库」这个原生标签,上传文件后只会刷新它的内容,咱们自己加的自定义标签根本不会自动同步更新。不过别慌,通过监听WP内置的上传事件+AJAX刷新就能搞定,下面一步步来:
第一步:监听上传完成的事件
WordPress媒体上传器有个uploaded事件,文件上传成功后会自动触发它。咱们用jQuery绑定这个事件,触发刷新逻辑:
jQuery(document).ready(function($) { // 监听上传完成事件 $(document).on('uploaded', function(e, attachment) { // 调用刷新自定义标签的函数 refreshCustomMediaTab(); }); });
第二步:写个刷新标签内容的AJAX函数
接下来要写refreshCustomMediaTab函数,通过AJAX拉取最新的内容,替换掉自定义标签里的旧内容。假设你的自定义标签内容容器ID是custom-media-tab-content,代码大概是这样:
function refreshCustomMediaTab() { jQuery.ajax({ url: customMediaData.ajaxurl, // 后面会用WP的localize传递这个地址 type: 'POST', data: { action: 'refresh_custom_media_tab', // 自定义的AJAX动作名 nonce: customMediaData.nonce // 安全验证用的nonce,后面会生成 }, success: function(response) { // 把新内容替换到容器里 jQuery('#custom-media-tab-content').html(response); } }); }
第三步:在PHP里注册AJAX处理逻辑
然后去主题的functions.php或者你的插件文件里,写对应的AJAX处理函数,用来生成最新的自定义标签内容:
// 注册AJAX动作,支持登录用户和未登录用户(按需选择) add_action('wp_ajax_refresh_custom_media_tab', 'refresh_custom_media_tab_callback'); add_action('wp_ajax_nopriv_refresh_custom_media_tab', 'refresh_custom_media_tab_callback'); function refresh_custom_media_tab_callback() { // 先验证nonce,安全第一! check_ajax_referer('custom_media_nonce_action', 'nonce'); // 这里写生成自定义标签内容的逻辑,比如查询最新上传的媒体 ob_start(); $latest_attachments = get_posts(array( 'post_type' => 'attachment', 'post_status' => 'inherit', 'posts_per_page' => 10, 'orderby' => 'date', 'order' => 'DESC' )); if ($latest_attachments) { foreach ($latest_attachments as $attach) { echo wp_get_attachment_image($attach->ID, 'medium') . '<p>' . get_the_title($attach->ID) . '</p>'; } } else { echo '<p>暂无媒体文件</p>'; } $fresh_content = ob_get_clean(); echo $fresh_content; wp_die(); // 必须用这个结束AJAX请求,不然会返回多余内容 }
第四步:传递必要的参数给前端JS
别忘了把AJAX地址和nonce值传递给前端,不然JS里拿不到这些信息。在functions.php里加这段代码:
function enqueue_custom_media_scripts() { // 注册并加载咱们的自定义JS文件 wp_enqueue_script('custom-media-js', get_template_directory_uri() . '/js/custom-media.js', array('jquery'), '1.0', true); // 把需要的参数传递给JS wp_localize_script('custom-media-js', 'customMediaData', array( 'ajaxurl' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('custom_media_nonce_action') )); } add_action('admin_enqueue_scripts', 'enqueue_custom_media_scripts');
额外小技巧:针对当前标签优化
如果你想更贴心一点,可以判断当前是否正显示自定义标签,再做对应的UI提示,比如高亮新上传的内容:
$(document).on('uploaded', function(e, attachment) { refreshCustomMediaTab(); // 如果当前正看着自定义标签,就给新内容加个高亮 if ($('.media-menu-item.active').attr('href') === '#custom-media-tab') { $('#custom-media-tab-content > div:first').addClass('new-upload-highlight'); } });
这样操作后,每次上传完文件,自定义标签的内容就会自动刷新,再也不用手动重载页面啦!
内容的提问来源于stack exchange,提问作者jaguwalapratik
相关产品推荐
相关产品推荐

