WordPress图片自动添加Alt和title教程

[复制链接]
550 0
admin 发表于 2022-4-8 13:47:59 | 只看该作者 |只看大图 |阅读模式 打印 上一主题 下一主题
WordPress上传图片时图片不会自动添加ALT和TITLE,这样非常不利于SEO优化,手动添加又非常免费。微范儿分享一段WordPress图片自动添加Alt和title方法。
将下面的代码添加到当前主题函数模板functions.php中:
————————代码部分——————————————————————————
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 ) ) {
$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 );
// Sanitize the title:  capitalize first letter of every word (other letters lower case):
$my_image_title = ucwords( strtolower( $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_excerpt'=> $my_image_title,// Set image Caption (Excerpt) 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 );
}
}

————————代码部分——————————————————————————
代码可以过滤掉图片名称中的空格等多余元素,对之前上传的图片无效。
请点击此处下载

请先注册会员后再进行下载

已注册会员,请先登录后下载

网盘密码:rvqb 
下载次数:0  文件大小:网盘资源  售价:30 下载币
下载权限: 不限 


收藏
收藏0
回复

使用道具 举报

*滑块验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

专注源码资源免费分享
只要有下载币全站均可下

私人收藏网站非买卖网站

周一至周日9:00-23:00

反馈建议

282865654@qq.com 在线QQ咨询

赞助我们享尊贵分享

Powered by X3.3© 2019-2029 3se.cc Inc.( 京ICP备14050279号-2