WordPress上传图片时实现文件名空格转连字符、过滤标点的方案咨询
WordPress 上传图片文件名规范化修复方案
你原有代码不生效的核心原因有两点:
- 检测到文章关联关系后直接返回了未做处理的原始文章标题作为文件名,后续的清理逻辑完全没有执行
- 原有代码中
$my_image_title . - uniqid()存在语法错误,对应逻辑分支无法正常触发
修改后可直接使用的完整代码
function file_renamer( $filename ) { $info = pathinfo( $filename ); $ext = empty( $info['extension'] ) ? '' : '.' . $info['extension']; // 检测上传图片所属的文章ID if( array_key_exists("post_id", $_POST) ) { $post_id = $_POST["post_id"]; $post = get_post($post_id); if( $post ) { // 内置函数自动把标题转为URL友好格式:空格转连字符、去除所有标点特殊字符 $clean_title = sanitize_title( $post->post_title ); // 追加唯一ID避免同文章上传多张图片时重名覆盖 return $clean_title . '-' . uniqid() . $ext; } } // 没有关联文章时保留原文件名,可按需调整此处逻辑 return $filename; } add_filter( 'sanitize_file_name', 'file_renamer', 10, 1 ); /* Automatically set the image Title, Alt-Text, Caption & Description upon upload */ add_action( 'add_attachment', 'my_set_image_meta_upon_image_upload' ); function my_set_image_meta_upon_image_upload( $post_ID ) { // Check if uploaded file is an image, else do nothing if ( wp_attachment_is_image( $post_ID ) ) { // Get the parent post ID, if there is one if( isset($_REQUEST['post_id']) ) { $post_id = $_REQUEST['post_id']; } else { $post_id = false; } if ($post_id != false) { $my_image_title = get_the_title($post_id); } else { $my_image_title = get_post( $post_ID )->post_title; } // Sanitize the title: remove hyphens, underscores & extra spaces: $my_image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ', $my_image_title ); // Create an array with the image meta (Title, Caption, Description) to be updated // Note: comment out the Excerpt/Caption or Content/Description lines if not needed $my_image_meta = array( 'ID' => $post_ID, // Specify the image (ID) to be updated 'post_title' => $my_image_title, // Set image Title to sanitized title 'post_content' => $my_image_title, // Set image Description (Content) to sanitized title ); // Set the image Alt-Text update_post_meta( $post_ID, '_wp_attachment_image_alt', $my_image_title ); // Set the image meta (e.g. Title, Excerpt, Content) wp_update_post( $my_image_meta ); } }
效果说明
修改后图片的alt、title、描述字段填充效果和之前完全一致,仅文件名部分会自动完成规范化处理:空格替换为连字符、所有标点和特殊字符自动清除,同时追加的唯一ID可以避免同一篇文章上传多张图片时出现重名覆盖的问题。
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

