如何修改WordPress图片上传过滤函数,让错误链接以HTML形式显示
解决WordPress上传错误信息中HTML链接显示为纯文本的问题
问题原因
WordPress在渲染上传错误提示时,会自动对wp_handle_upload_prefilter返回的错误信息执行esc_html()转义,导致HTML标签被转换为纯文本,无法正常显示链接。
修改方案
我们需要通过两步实现带HTML链接的错误提示:
- 在上传预过滤函数中返回自定义错误标识,而非直接返回带HTML的内容;
- 通过
wp_upload_error_msg过滤器替换错误标识为带安全HTML的提示内容。
修改后的完整代码
function filter_image_pre_upload($file) { $mimes = array( 'image/jpeg', 'image/png', 'image/gif' ); if( !in_array( $file['type'], $mimes ) ) return $file; $img = getimagesize( $file['tmp_name'] ); $maximum = array( 'width' => 1200, 'height' => 1500 ); if ( $img[0] > $maximum['width'] ) { $file['error'] = sprintf( 'image_too_large_width:%d', $img[0] ); } elseif ( $img[1] > $maximum['height'] ) { $file['error'] = sprintf( 'image_too_large_height:%d', $img[1] ); } return $file; } add_filter('wp_handle_upload_prefilter', 'filter_image_pre_upload', 20); // 自定义上传错误信息渲染 function custom_upload_error_msg($error_msg, $error_code) { // 处理宽度超限错误 if (strpos($error_msg, 'image_too_large_width:') === 0) { $img_width = (int) str_replace('image_too_large_width:', '', $error_msg); $error_msg = sprintf( '你尝试上传的图片尺寸过大。你的图片宽度为 %dpx,允许的最大尺寸为宽1200px × 高1500px。请访问 <a href="https://example.com">图片裁剪调整工具</a>来修改图片,或联系 <a href="mailto:me@example.com">管理员</a>获取帮助。', $img_width ); return wp_kses_post($error_msg); } // 处理高度超限错误 elseif (strpos($error_msg, 'image_too_large_height:') === 0) { $img_height = (int) str_replace('image_too_large_height:', '', $error_msg); $error_msg = sprintf( '你尝试上传的图片尺寸过大。你的图片高度为 %dpx,允许的最大尺寸为宽1200px × 高1500px。请访问 <a href="https://example.com">图片裁剪调整工具</a>来修改图片,或联系 <a href="mailto:me@example.com">管理员</a>获取帮助。', $img_height ); return wp_kses_post($error_msg); } // 保留默认错误处理逻辑 return $error_msg; } add_filter('wp_upload_error_msg', 'custom_upload_error_msg', 10, 2);
关键说明
- 使用
wp_kses_post()函数过滤HTML内容,既保留了合法的HTML标签(如<a>),又能防止XSS安全风险; - 通过自定义错误标识,避免了直接匹配错误文本的不可靠性,确保只有我们指定的错误会被替换为带HTML的提示。
内容的提问来源于stack exchange,提问作者John
相关产品推荐
相关产品推荐

