正文:
为了简化操作过程,我们可以为 WordPress
文章上传图片时自动重命名图片名称。之前的文章可以使用时间或 MD5
生成数字来重命名所有媒体文件。在文章编辑时上传添加图片时,我们可以自动将图片重命名为文章标题,并自动填充图片的 ALT
、说明、替代文本和描述等相关信息。只需将以下代码添加到当前主题的functions
.php
文件中即可。
代码如下:
// https
://www
.huizhanii
.com
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
);
}
}
提示:上面的方法只适合在文章编辑页面使用,如果在媒体库上传无效。另外,图片名称为中文貌似有的主机环境并不支持。
转载请注明:汇站网 » (WordPress
教程)纯代码实现上传图片时自动将图片重命名为文章标题