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

作者 : 星辰 本文共1388个字,预计阅读时间需要4分钟 发布时间: 2020-10-6 共951人阅读

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 );
} 
}

代码可以过滤掉图片名称中的空格等多余元素,对之前上传的图片无效。

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长!
2. 分享目的仅供大家学习和交流,您必须在下载后24小时内删除!
3. 不得使用于非法商业用途,不得违反国家法律。否则后果自负!
4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解!
5. 如有链接无法下载、失效或广告,请联系管理员处理!
6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需!
7. 如遇到加密压缩包,默认解压密码为"www.vfaner.com",如遇到无法解压的请联系管理员!

微范儿 » WordPress图片自动添加Alt和title教程

常见问题FAQ

免费下载或者VIP会员专享资源能否直接商用?
本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。
下载不了或者解压包需要密码?
蓝奏云下载不了一般改一下后缀就可以下载了,比如t改成i或者x等,很早之前的资源可能有几个需要解压密码,默认就是本站域名www.vfaner.com
资源经过测试有bug或者不能使用?
资源都是各大平台和收费平台搜集的,遇到不能使用添加QQ7940758进行反馈及时删除该资源