为 WordPress 文章上传添加图片时自动重命名图片名称,可以简化操作过程序,之前的文章可以用时间或者MD5生成数字重命名所有媒体文件。 这里再分享一段,在文章编辑时上传添加图片,自动将图片重命名为文章标题,并自动填充图片ATL、说明、替代文本、描述等相关信息。
将下面代码添加到当前主题函数模板functions.php中: - function file_renamer( $filename ) {
- $info = pathinfo( $filename );
- $ext = empty( $info['extension'] ) ? '' : '.' . $info['extension'];
- $name = basename( $filename, $ext );
- if( $post_id = array_key_exists( "post_id", $_POST) ? $_POST["post_id"] : null ) {
- if($post = get_post($post_id)) {
- return $post->post_title . $ext;
- }
- }
-
- $my_image_title = $post;
- $file['name'] = $my_image_title . - uniqid() . $ext; // uniqid method
- // $file['name'] = md5($name) . $ext; // md5 method
- // $file['name'] = base64_encode( $name ) . $ext; // base64 method
- return $filename;
- }
-
- add_filter( 'sanitize_file_name', 'file_renamer', 10, 1 );
-
- // 上传时自动设置图像标题、替代文本、标题和描述
- add_action( 'add_attachment', 'my_set_image_meta_upon_image_upload' );
- function my_set_image_meta_upon_image_upload( $post_ID ) {
-
- // 检查上传的文件是否是图片
- if ( wp_attachment_is_image( $post_ID ) ) {
-
- 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;
- }
-
- // 清理标题**殊字符
- $my_image_title = preg_replace( '%\s*[-_\s]+\s*%', ' ', $my_image_title );
-
- // 将第一个字母大写
- $my_image_title = ucwords( strtolower( $my_image_title ) );
-
- // 创建包含标题、说明、描述的数组
- $my_image_meta = array(
- 'ID' => $post_ID, // ID
- 'post_title' => $my_image_title, // 图像标题
- 'post_excerpt' => $my_image_title, // 图像说明
- 'post_content' => $my_image_title, // 图像描述
- );
-
- // 添加图像 Alt
- update_post_meta( $post_ID, '_wp_attachment_image_alt', $my_image_title );
-
- // 添加标题、说明、描述
- wp_update_post( $my_image_meta );
- }
- }
复制代码提示:上面的方法只适合在文章编辑页面使用,如果在媒体库上传无效。另外,图片名称为中文貌似有的主机环境并不支持。
|